Skip to main content

alloc/collections/btree/
map.rs

1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::error::Error;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FusedIterator, TrustedLen};
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use super::borrow::DormantMutRef;
13use super::dedup_sorted_iter::DedupSortedIter;
14use super::navigate::{LazyLeafRange, LeafRange};
15use super::node::ForceResult::*;
16use super::node::{self, Handle, NodeRef, Root, marker};
17use super::search::SearchBound;
18use super::search::SearchResult::*;
19use super::set_val::SetValZST;
20use crate::alloc::{AllocatorClone, Global};
21use crate::vec::Vec;
22
23mod entry;
24
25use Entry::*;
26#[stable(feature = "rust1", since = "1.0.0")]
27pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28
29/// Minimum number of elements in a node that is not a root.
30/// We might temporarily have fewer elements during methods.
31pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32
33// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
34// - Keys must appear in ascending order (according to the key's type).
35// - Every non-leaf node contains at least 1 element (has at least 2 children).
36// - Every non-root node contains at least MIN_LEN elements.
37//
38// An empty map is represented either by the absence of a root node or by a
39// root node that is an empty leaf.
40
41/// An ordered map based on a [B-Tree].
42///
43/// Given a key type with a [total order], an ordered map stores its entries in key order.
44/// That means that keys must be of a type that implements the [`Ord`] trait,
45/// such that two keys can always be compared to determine their [`Ordering`].
46/// Examples of keys with a total order are strings with lexicographical order,
47/// and numbers with their natural order.
48///
49/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::into_iter`], [`BTreeMap::values`], or
50/// [`BTreeMap::keys`] produce their items in key order, and take worst-case logarithmic and
51/// amortized constant time per item returned.
52///
53/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
54/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
55/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
57/// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
58/// include panics, incorrect results, aborts, memory leaks, and non-termination.
59///
60/// # Examples
61///
62/// ```
63/// use std::collections::BTreeMap;
64///
65/// // type inference lets us omit an explicit type signature (which
66/// // would be `BTreeMap<&str, &str>` in this example).
67/// let mut movie_reviews = BTreeMap::new();
68///
69/// // review some movies.
70/// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
71/// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
72/// movie_reviews.insert("The Godfather",      "Very enjoyable.");
73/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
74///
75/// // check for a specific one.
76/// if !movie_reviews.contains_key("Les Misérables") {
77///     println!("We've got {} reviews, but Les Misérables ain't one.",
78///              movie_reviews.len());
79/// }
80///
81/// // oops, this review has a lot of spelling mistakes, let's delete it.
82/// movie_reviews.remove("The Blues Brothers");
83///
84/// // look up the values associated with some keys.
85/// let to_find = ["Up!", "Office Space"];
86/// for movie in &to_find {
87///     match movie_reviews.get(movie) {
88///        Some(review) => println!("{movie}: {review}"),
89///        None => println!("{movie} is unreviewed.")
90///     }
91/// }
92///
93/// // Look up the value for a key (will panic if the key is not found).
94/// println!("Movie review: {}", movie_reviews["Office Space"]);
95///
96/// // iterate over everything.
97/// for (movie, review) in &movie_reviews {
98///     println!("{movie}: \"{review}\"");
99/// }
100/// ```
101///
102/// A `BTreeMap` with a known list of items can be initialized from an array:
103///
104/// ```
105/// use std::collections::BTreeMap;
106///
107/// let solar_distance = BTreeMap::from([
108///     ("Mercury", 0.4),
109///     ("Venus", 0.7),
110///     ("Earth", 1.0),
111///     ("Mars", 1.5),
112/// ]);
113/// ```
114///
115/// ## `Entry` API
116///
117/// `BTreeMap` implements an [`Entry API`], which allows for complex
118/// methods of getting, setting, updating and removing keys and their values:
119///
120/// [`Entry API`]: BTreeMap::entry
121///
122/// ```
123/// use std::collections::BTreeMap;
124///
125/// // type inference lets us omit an explicit type signature (which
126/// // would be `BTreeMap<&str, u8>` in this example).
127/// let mut player_stats = BTreeMap::new();
128///
129/// fn random_stat_buff() -> u8 {
130///     // could actually return some random value here - let's just return
131///     // some fixed value for now
132///     42
133/// }
134///
135/// // insert a key only if it doesn't already exist
136/// player_stats.entry("health").or_insert(100);
137///
138/// // insert a key using a function that provides a new value only if it
139/// // doesn't already exist
140/// player_stats.entry("defence").or_insert_with(random_stat_buff);
141///
142/// // update a key, guarding against the key possibly not being set
143/// let stat = player_stats.entry("attack").or_insert(100);
144/// *stat += random_stat_buff();
145///
146/// // modify an entry before an insert with in-place mutation
147/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
148/// ```
149///
150/// # Background
151///
152/// A B-tree is (like) a [binary search tree], but adapted to the natural granularity that modern
153/// machines like to consume data at. This means that each node contains an entire array of elements,
154/// instead of just a single element.
155///
156/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
157/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
158/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum number of
159/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
160/// is done is *very* inefficient for modern computer architectures. In particular, every element
161/// is stored in its own individually heap-allocated node. This means that every single insertion
162/// triggers a heap-allocation, and every comparison is a potential cache-miss due to the indirection.
163/// Since both heap-allocations and cache-misses are notably expensive in practice, we are forced to,
164/// at the very least, reconsider the BST strategy.
165///
166/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
167/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
168/// searches. However, this does mean that searches will have to do *more* comparisons on average.
169/// The precise number of comparisons depends on the node search strategy used. For optimal cache
170/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
171/// the node using binary search. As a compromise, one could also perform a linear search
172/// that initially only checks every i<sup>th</sup> element for some choice of i.
173///
174/// Currently, our implementation simply performs naive linear search. This provides excellent
175/// performance on *small* nodes of elements which are cheap to compare. However in the future we
176/// would like to further explore choosing the optimal search strategy based on the choice of B,
177/// and possibly other factors. Using linear search, searching for a random element is expected
178/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
179/// however, performance is excellent.
180///
181/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
182/// [binary search tree]: https://en.wikipedia.org/wiki/Binary_search_tree
183/// [total order]: https://en.wikipedia.org/wiki/Total_order
184/// [`Cell`]: core::cell::Cell
185/// [`RefCell`]: core::cell::RefCell
186#[stable(feature = "rust1", since = "1.0.0")]
187#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
188#[rustc_insignificant_dtor]
189pub struct BTreeMap<
190    K,
191    V,
192    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
193> {
194    root: Option<Root<K, V>>,
195    length: usize,
196    /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
197    // Although some of the accessory types store a copy of the allocator, the nodes do not.
198    // Because allocations will remain live as long as any copy (like this one) of the allocator
199    // is live, it's unnecessary to store the allocator in each node.
200    pub(super) alloc: ManuallyDrop<A>,
201    // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
202    _marker: PhantomData<crate::boxed::Box<(K, V), A>>,
203}
204
205#[stable(feature = "btree_drop", since = "1.7.0")]
206unsafe impl<#[may_dangle] K, #[may_dangle] V, A: AllocatorClone> Drop for BTreeMap<K, V, A> {
207    fn drop(&mut self) {
208        // ignore-tidy-undocumented-unsafe
209        drop(unsafe { ptr::read(self) }.into_iter())
210    }
211}
212
213// FIXME: This implementation is "wrong", but changing it would be a breaking change.
214// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
215// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
216// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
217#[stable(feature = "btree_unwindsafe", since = "1.64.0")]
218impl<K, V, A: AllocatorClone> core::panic::UnwindSafe for BTreeMap<K, V, A>
219where
220    A: core::panic::UnwindSafe,
221    K: core::panic::RefUnwindSafe,
222    V: core::panic::RefUnwindSafe,
223{
224}
225
226#[stable(feature = "rust1", since = "1.0.0")]
227impl<K: Clone, V: Clone, A: AllocatorClone> Clone for BTreeMap<K, V, A> {
228    fn clone(&self) -> BTreeMap<K, V, A> {
229        fn clone_subtree<'a, K: Clone, V: Clone, A: AllocatorClone>(
230            node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
231            alloc: A,
232        ) -> BTreeMap<K, V, A>
233        where
234            K: 'a,
235            V: 'a,
236        {
237            match node.force() {
238                Leaf(leaf) => {
239                    let mut out_tree = BTreeMap {
240                        root: Some(Root::new(alloc.clone())),
241                        length: 0,
242                        alloc: ManuallyDrop::new(alloc),
243                        _marker: PhantomData,
244                    };
245
246                    {
247                        let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
248                        let mut out_node = match root.borrow_mut().force() {
249                            Leaf(leaf) => leaf,
250                            Internal(_) => unreachable!(),
251                        };
252
253                        let mut in_edge = leaf.first_edge();
254                        while let Ok(kv) = in_edge.right_kv() {
255                            let (k, v) = kv.into_kv();
256                            in_edge = kv.right_edge();
257
258                            out_node.push(k.clone(), v.clone());
259                            out_tree.length += 1;
260                        }
261                    }
262
263                    out_tree
264                }
265                Internal(internal) => {
266                    let mut out_tree =
267                        clone_subtree(internal.first_edge().descend(), alloc.clone());
268
269                    {
270                        let out_root = out_tree.root.as_mut().unwrap();
271                        let mut out_node = out_root.push_internal_level(alloc.clone());
272                        let mut in_edge = internal.first_edge();
273                        while let Ok(kv) = in_edge.right_kv() {
274                            let (k, v) = kv.into_kv();
275                            in_edge = kv.right_edge();
276
277                            let k = (*k).clone();
278                            let v = (*v).clone();
279                            let subtree = clone_subtree(in_edge.descend(), alloc.clone());
280
281                            // We can't destructure subtree directly
282                            // because BTreeMap implements Drop
283                            let (subroot, sublength) = {
284                                let subtree = ManuallyDrop::new(subtree);
285                                // ignore-tidy-undocumented-unsafe
286                                let root = unsafe { ptr::read(&subtree.root) };
287                                let length = subtree.length;
288                                (root, length)
289                            };
290
291                            out_node.push(
292                                k,
293                                v,
294                                subroot.unwrap_or_else(|| Root::new(alloc.clone())),
295                            );
296                            out_tree.length += 1 + sublength;
297                        }
298                    }
299
300                    out_tree
301                }
302            }
303        }
304
305        if self.is_empty() {
306            BTreeMap::new_in((*self.alloc).clone())
307        } else {
308            clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
309        }
310    }
311}
312
313// Internal functionality for `BTreeSet`.
314impl<K, A: AllocatorClone> BTreeMap<K, SetValZST, A> {
315    pub(super) fn replace(&mut self, key: K) -> Option<K>
316    where
317        K: Ord,
318    {
319        let (map, dormant_map) = DormantMutRef::new(self);
320        let root_node =
321            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
322        match root_node.search_tree::<K>(&key) {
323            Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
324            GoDown(handle) => {
325                VacantEntry {
326                    key,
327                    handle: Some(handle),
328                    dormant_map,
329                    alloc: (*map.alloc).clone(),
330                    _marker: PhantomData,
331                }
332                .insert(SetValZST);
333                None
334            }
335        }
336    }
337
338    pub(super) fn get_or_insert_with<Q: ?Sized, F>(&mut self, q: &Q, f: F) -> &K
339    where
340        K: Borrow<Q> + Ord,
341        Q: Ord,
342        F: FnOnce(&Q) -> K,
343    {
344        let (map, dormant_map) = DormantMutRef::new(self);
345        let root_node =
346            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
347        match root_node.search_tree(q) {
348            Found(handle) => handle.into_kv_mut().0,
349            GoDown(handle) => {
350                let key = f(q);
351                assert!(*key.borrow() == *q, "new value is not equal");
352                VacantEntry {
353                    key,
354                    handle: Some(handle),
355                    dormant_map,
356                    alloc: (*map.alloc).clone(),
357                    _marker: PhantomData,
358                }
359                .insert_entry(SetValZST)
360                .into_key()
361            }
362        }
363    }
364}
365
366/// An iterator over the entries of a `BTreeMap`.
367///
368/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
369/// documentation for more.
370///
371/// [`iter`]: BTreeMap::iter
372#[must_use = "iterators are lazy and do nothing unless consumed"]
373#[stable(feature = "rust1", since = "1.0.0")]
374pub struct Iter<'a, K: 'a, V: 'a> {
375    range: LazyLeafRange<marker::Immut<'a>, K, V>,
376    length: usize,
377}
378
379#[stable(feature = "collection_debug", since = "1.17.0")]
380impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        f.debug_list().entries(self.clone()).finish()
383    }
384}
385
386#[stable(feature = "default_iters", since = "1.70.0")]
387impl<'a, K: 'a, V: 'a> Default for Iter<'a, K, V> {
388    /// Creates an empty `btree_map::Iter`.
389    ///
390    /// ```
391    /// # use std::collections::btree_map;
392    /// let iter: btree_map::Iter<'_, u8, u8> = Default::default();
393    /// assert_eq!(iter.len(), 0);
394    /// ```
395    fn default() -> Self {
396        Iter { range: Default::default(), length: 0 }
397    }
398}
399
400/// A mutable iterator over the entries of a `BTreeMap`.
401///
402/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
403/// documentation for more.
404///
405/// [`iter_mut`]: BTreeMap::iter_mut
406#[must_use = "iterators are lazy and do nothing unless consumed"]
407#[stable(feature = "rust1", since = "1.0.0")]
408pub struct IterMut<'a, K: 'a, V: 'a> {
409    range: LazyLeafRange<marker::ValMut<'a>, K, V>,
410    length: usize,
411
412    // Be invariant in `K` and `V`
413    _marker: PhantomData<&'a mut (K, V)>,
414}
415
416#[stable(feature = "collection_debug", since = "1.17.0")]
417impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        let range = Iter { range: self.range.reborrow(), length: self.length };
420        f.debug_list().entries(range).finish()
421    }
422}
423
424#[stable(feature = "default_iters", since = "1.70.0")]
425impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> {
426    /// Creates an empty `btree_map::IterMut`.
427    ///
428    /// ```
429    /// # use std::collections::btree_map;
430    /// let iter: btree_map::IterMut<'_, u8, u8> = Default::default();
431    /// assert_eq!(iter.len(), 0);
432    /// ```
433    fn default() -> Self {
434        IterMut { range: Default::default(), length: 0, _marker: PhantomData {} }
435    }
436}
437
438/// An owning iterator over the entries of a `BTreeMap`, sorted by key.
439///
440/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
441/// (provided by the [`IntoIterator`] trait). See its documentation for more.
442///
443/// [`into_iter`]: IntoIterator::into_iter
444#[stable(feature = "rust1", since = "1.0.0")]
445#[rustc_insignificant_dtor]
446pub struct IntoIter<
447    K,
448    V,
449    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
450> {
451    range: LazyLeafRange<marker::Dying, K, V>,
452    length: usize,
453    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
454    alloc: A,
455}
456
457impl<K, V, A: AllocatorClone> IntoIter<K, V, A> {
458    /// Returns an iterator of references over the remaining items.
459    #[inline]
460    pub(super) fn iter(&self) -> Iter<'_, K, V> {
461        Iter { range: self.range.reborrow(), length: self.length }
462    }
463}
464
465#[stable(feature = "collection_debug", since = "1.17.0")]
466impl<K: Debug, V: Debug, A: AllocatorClone> Debug for IntoIter<K, V, A> {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        f.debug_list().entries(self.iter()).finish()
469    }
470}
471
472#[stable(feature = "default_iters", since = "1.70.0")]
473impl<K, V, A> Default for IntoIter<K, V, A>
474where
475    A: AllocatorClone + Default,
476{
477    /// Creates an empty `btree_map::IntoIter`.
478    ///
479    /// ```
480    /// # use std::collections::btree_map;
481    /// let iter: btree_map::IntoIter<u8, u8> = Default::default();
482    /// assert_eq!(iter.len(), 0);
483    /// ```
484    fn default() -> Self {
485        IntoIter { range: Default::default(), length: 0, alloc: Default::default() }
486    }
487}
488
489/// An iterator over the keys of a `BTreeMap`.
490///
491/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
492/// documentation for more.
493///
494/// [`keys`]: BTreeMap::keys
495#[must_use = "iterators are lazy and do nothing unless consumed"]
496#[stable(feature = "rust1", since = "1.0.0")]
497pub struct Keys<'a, K, V> {
498    inner: Iter<'a, K, V>,
499}
500
501#[stable(feature = "collection_debug", since = "1.17.0")]
502impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        f.debug_list().entries(self.clone()).finish()
505    }
506}
507
508/// An iterator over the values of a `BTreeMap`.
509///
510/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
511/// documentation for more.
512///
513/// [`values`]: BTreeMap::values
514#[must_use = "iterators are lazy and do nothing unless consumed"]
515#[stable(feature = "rust1", since = "1.0.0")]
516pub struct Values<'a, K, V> {
517    inner: Iter<'a, K, V>,
518}
519
520#[stable(feature = "collection_debug", since = "1.17.0")]
521impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523        f.debug_list().entries(self.clone()).finish()
524    }
525}
526
527/// A mutable iterator over the values of a `BTreeMap`.
528///
529/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
530/// documentation for more.
531///
532/// [`values_mut`]: BTreeMap::values_mut
533#[must_use = "iterators are lazy and do nothing unless consumed"]
534#[stable(feature = "map_values_mut", since = "1.10.0")]
535pub struct ValuesMut<'a, K, V> {
536    inner: IterMut<'a, K, V>,
537}
538
539#[stable(feature = "map_values_mut", since = "1.10.0")]
540impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
543    }
544}
545
546/// An owning iterator over the keys of a `BTreeMap`.
547///
548/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
549/// See its documentation for more.
550///
551/// [`into_keys`]: BTreeMap::into_keys
552#[must_use = "iterators are lazy and do nothing unless consumed"]
553#[stable(feature = "map_into_keys_values", since = "1.54.0")]
554pub struct IntoKeys<
555    K,
556    V,
557    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
558> {
559    inner: IntoIter<K, V, A>,
560}
561
562#[stable(feature = "map_into_keys_values", since = "1.54.0")]
563impl<K: fmt::Debug, V, A: AllocatorClone> fmt::Debug for IntoKeys<K, V, A> {
564    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565        f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
566    }
567}
568
569/// An owning iterator over the values of a `BTreeMap`.
570///
571/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
572/// See its documentation for more.
573///
574/// [`into_values`]: BTreeMap::into_values
575#[must_use = "iterators are lazy and do nothing unless consumed"]
576#[stable(feature = "map_into_keys_values", since = "1.54.0")]
577pub struct IntoValues<
578    K,
579    V,
580    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
581> {
582    inner: IntoIter<K, V, A>,
583}
584
585#[stable(feature = "map_into_keys_values", since = "1.54.0")]
586impl<K, V: fmt::Debug, A: AllocatorClone> fmt::Debug for IntoValues<K, V, A> {
587    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
589    }
590}
591
592/// An iterator over a sub-range of entries in a `BTreeMap`.
593///
594/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
595/// documentation for more.
596///
597/// [`range`]: BTreeMap::range
598#[must_use = "iterators are lazy and do nothing unless consumed"]
599#[stable(feature = "btree_range", since = "1.17.0")]
600pub struct Range<'a, K: 'a, V: 'a> {
601    inner: LeafRange<marker::Immut<'a>, K, V>,
602}
603
604#[stable(feature = "collection_debug", since = "1.17.0")]
605impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
606    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607        f.debug_list().entries(self.clone()).finish()
608    }
609}
610
611/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
612///
613/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
614/// documentation for more.
615///
616/// [`range_mut`]: BTreeMap::range_mut
617#[must_use = "iterators are lazy and do nothing unless consumed"]
618#[stable(feature = "btree_range", since = "1.17.0")]
619pub struct RangeMut<'a, K: 'a, V: 'a> {
620    inner: LeafRange<marker::ValMut<'a>, K, V>,
621
622    // Be invariant in `K` and `V`
623    _marker: PhantomData<&'a mut (K, V)>,
624}
625
626#[stable(feature = "collection_debug", since = "1.17.0")]
627impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629        let range = Range { inner: self.inner.reborrow() };
630        f.debug_list().entries(range).finish()
631    }
632}
633
634impl<K, V> BTreeMap<K, V> {
635    /// Makes a new, empty `BTreeMap`.
636    ///
637    /// Does not allocate anything on its own.
638    ///
639    /// # Examples
640    ///
641    /// ```
642    /// use std::collections::BTreeMap;
643    ///
644    /// let mut map = BTreeMap::new();
645    ///
646    /// // entries can now be inserted into the empty map
647    /// map.insert(1, "a");
648    /// ```
649    #[stable(feature = "rust1", since = "1.0.0")]
650    #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
651    #[inline]
652    #[must_use]
653    pub const fn new() -> BTreeMap<K, V> {
654        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global), _marker: PhantomData }
655    }
656}
657
658impl<K, V, A: AllocatorClone> BTreeMap<K, V, A> {
659    /// Clears the map, removing all elements.
660    ///
661    /// # Examples
662    ///
663    /// ```
664    /// use std::collections::BTreeMap;
665    ///
666    /// let mut a = BTreeMap::new();
667    /// a.insert(1, "a");
668    /// a.clear();
669    /// assert!(a.is_empty());
670    /// ```
671    #[stable(feature = "rust1", since = "1.0.0")]
672    pub fn clear(&mut self) {
673        // avoid moving the allocator
674        drop(BTreeMap {
675            root: self.root.take(),
676            length: mem::replace(&mut self.length, 0),
677            alloc: self.alloc.clone(),
678            _marker: PhantomData,
679        });
680    }
681
682    /// Makes a new empty BTreeMap with a reasonable choice for B.
683    ///
684    /// # Examples
685    ///
686    /// ```
687    /// # #![feature(allocator_api)]
688    /// # #![feature(btreemap_alloc)]
689    ///
690    /// use std::collections::BTreeMap;
691    /// use std::alloc::Global;
692    ///
693    /// let map: BTreeMap<i32, i32> = BTreeMap::new_in(Global);
694    /// ```
695    #[unstable(feature = "btreemap_alloc", issue = "32838")]
696    #[must_use]
697    pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
698        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
699    }
700}
701
702impl<K, V, A: AllocatorClone> BTreeMap<K, V, A> {
703    /// Returns a reference to the value corresponding to the key.
704    ///
705    /// The key may be any borrowed form of the map's key type, but the ordering
706    /// on the borrowed form *must* match the ordering on the key type.
707    ///
708    /// # Examples
709    ///
710    /// ```
711    /// use std::collections::BTreeMap;
712    ///
713    /// let mut map = BTreeMap::new();
714    /// map.insert(1, "a");
715    /// assert_eq!(map.get(&1), Some(&"a"));
716    /// assert_eq!(map.get(&2), None);
717    /// ```
718    #[stable(feature = "rust1", since = "1.0.0")]
719    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
720    where
721        K: Borrow<Q> + Ord,
722        Q: Ord,
723    {
724        let root_node = self.root.as_ref()?.reborrow();
725        match root_node.search_tree(key) {
726            Found(handle) => Some(handle.into_kv().1),
727            GoDown(_) => None,
728        }
729    }
730
731    /// Returns the key-value pair corresponding to the supplied key. This is
732    /// potentially useful:
733    /// - for key types where non-identical keys can be considered equal;
734    /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
735    /// - for getting a reference to a key with the same lifetime as the collection.
736    ///
737    /// The supplied key may be any borrowed form of the map's key type, but the ordering
738    /// on the borrowed form *must* match the ordering on the key type.
739    ///
740    /// # Examples
741    ///
742    /// ```
743    /// use std::cmp::Ordering;
744    /// use std::collections::BTreeMap;
745    ///
746    /// #[derive(Clone, Copy, Debug)]
747    /// struct S {
748    ///     id: u32,
749    /// #   #[allow(unused)] // prevents a "field `name` is never read" error
750    ///     name: &'static str, // ignored by equality and ordering operations
751    /// }
752    ///
753    /// impl PartialEq for S {
754    ///     fn eq(&self, other: &S) -> bool {
755    ///         self.id == other.id
756    ///     }
757    /// }
758    ///
759    /// impl Eq for S {}
760    ///
761    /// impl PartialOrd for S {
762    ///     fn partial_cmp(&self, other: &S) -> Option<Ordering> {
763    ///         self.id.partial_cmp(&other.id)
764    ///     }
765    /// }
766    ///
767    /// impl Ord for S {
768    ///     fn cmp(&self, other: &S) -> Ordering {
769    ///         self.id.cmp(&other.id)
770    ///     }
771    /// }
772    ///
773    /// let j_a = S { id: 1, name: "Jessica" };
774    /// let j_b = S { id: 1, name: "Jess" };
775    /// let p = S { id: 2, name: "Paul" };
776    /// assert_eq!(j_a, j_b);
777    ///
778    /// let mut map = BTreeMap::new();
779    /// map.insert(j_a, "Paris");
780    /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
781    /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
782    /// assert_eq!(map.get_key_value(&p), None);
783    /// ```
784    #[stable(feature = "map_get_key_value", since = "1.40.0")]
785    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
786    where
787        K: Borrow<Q> + Ord,
788        Q: Ord,
789    {
790        let root_node = self.root.as_ref()?.reborrow();
791        match root_node.search_tree(k) {
792            Found(handle) => Some(handle.into_kv()),
793            GoDown(_) => None,
794        }
795    }
796
797    /// Returns the first key-value pair in the map.
798    /// The key in this pair is the minimum key in the map.
799    ///
800    /// # Examples
801    ///
802    /// ```
803    /// use std::collections::BTreeMap;
804    ///
805    /// let mut map = BTreeMap::new();
806    /// assert_eq!(map.first_key_value(), None);
807    /// map.insert(1, "b");
808    /// map.insert(2, "a");
809    /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
810    /// ```
811    #[stable(feature = "map_first_last", since = "1.66.0")]
812    pub fn first_key_value(&self) -> Option<(&K, &V)>
813    where
814        K: Ord,
815    {
816        let root_node = self.root.as_ref()?.reborrow();
817        root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
818    }
819
820    /// Returns the first entry in the map for in-place manipulation.
821    /// The key of this entry is the minimum key in the map.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// use std::collections::BTreeMap;
827    ///
828    /// let mut map = BTreeMap::new();
829    /// map.insert(1, "a");
830    /// map.insert(2, "b");
831    /// if let Some(mut entry) = map.first_entry() {
832    ///     if *entry.key() > 0 {
833    ///         entry.insert("first");
834    ///     }
835    /// }
836    /// assert_eq!(*map.get(&1).unwrap(), "first");
837    /// assert_eq!(*map.get(&2).unwrap(), "b");
838    /// ```
839    #[stable(feature = "map_first_last", since = "1.66.0")]
840    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
841    where
842        K: Ord,
843    {
844        let (map, dormant_map) = DormantMutRef::new(self);
845        let root_node = map.root.as_mut()?.borrow_mut();
846        let kv = root_node.first_leaf_edge().right_kv().ok()?;
847        Some(OccupiedEntry {
848            handle: kv.forget_node_type(),
849            dormant_map,
850            alloc: (*map.alloc).clone(),
851            _marker: PhantomData,
852        })
853    }
854
855    /// Removes and returns the first element in the map.
856    /// The key of this element is the minimum key that was in the map.
857    ///
858    /// # Examples
859    ///
860    /// Draining elements in ascending order, while keeping a usable map each iteration.
861    ///
862    /// ```
863    /// use std::collections::BTreeMap;
864    ///
865    /// let mut map = BTreeMap::new();
866    /// map.insert(1, "a");
867    /// map.insert(2, "b");
868    /// while let Some((key, _val)) = map.pop_first() {
869    ///     assert!(map.iter().all(|(k, _v)| *k > key));
870    /// }
871    /// assert!(map.is_empty());
872    /// ```
873    #[stable(feature = "map_first_last", since = "1.66.0")]
874    pub fn pop_first(&mut self) -> Option<(K, V)>
875    where
876        K: Ord,
877    {
878        self.first_entry().map(|entry| entry.remove_entry())
879    }
880
881    /// Returns the last key-value pair in the map.
882    /// The key in this pair is the maximum key in the map.
883    ///
884    /// # Examples
885    ///
886    /// ```
887    /// use std::collections::BTreeMap;
888    ///
889    /// let mut map = BTreeMap::new();
890    /// map.insert(1, "b");
891    /// map.insert(2, "a");
892    /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
893    /// ```
894    #[stable(feature = "map_first_last", since = "1.66.0")]
895    pub fn last_key_value(&self) -> Option<(&K, &V)>
896    where
897        K: Ord,
898    {
899        let root_node = self.root.as_ref()?.reborrow();
900        root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
901    }
902
903    /// Returns the last entry in the map for in-place manipulation.
904    /// The key of this entry is the maximum key in the map.
905    ///
906    /// # Examples
907    ///
908    /// ```
909    /// use std::collections::BTreeMap;
910    ///
911    /// let mut map = BTreeMap::new();
912    /// map.insert(1, "a");
913    /// map.insert(2, "b");
914    /// if let Some(mut entry) = map.last_entry() {
915    ///     if *entry.key() > 0 {
916    ///         entry.insert("last");
917    ///     }
918    /// }
919    /// assert_eq!(*map.get(&1).unwrap(), "a");
920    /// assert_eq!(*map.get(&2).unwrap(), "last");
921    /// ```
922    #[stable(feature = "map_first_last", since = "1.66.0")]
923    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
924    where
925        K: Ord,
926    {
927        let (map, dormant_map) = DormantMutRef::new(self);
928        let root_node = map.root.as_mut()?.borrow_mut();
929        let kv = root_node.last_leaf_edge().left_kv().ok()?;
930        Some(OccupiedEntry {
931            handle: kv.forget_node_type(),
932            dormant_map,
933            alloc: (*map.alloc).clone(),
934            _marker: PhantomData,
935        })
936    }
937
938    /// Removes and returns the last element in the map.
939    /// The key of this element is the maximum key that was in the map.
940    ///
941    /// # Examples
942    ///
943    /// Draining elements in descending order, while keeping a usable map each iteration.
944    ///
945    /// ```
946    /// use std::collections::BTreeMap;
947    ///
948    /// let mut map = BTreeMap::new();
949    /// map.insert(1, "a");
950    /// map.insert(2, "b");
951    /// while let Some((key, _val)) = map.pop_last() {
952    ///     assert!(map.iter().all(|(k, _v)| *k < key));
953    /// }
954    /// assert!(map.is_empty());
955    /// ```
956    #[stable(feature = "map_first_last", since = "1.66.0")]
957    pub fn pop_last(&mut self) -> Option<(K, V)>
958    where
959        K: Ord,
960    {
961        self.last_entry().map(|entry| entry.remove_entry())
962    }
963
964    /// Returns `true` if the map contains a value for the specified key.
965    ///
966    /// The key may be any borrowed form of the map's key type, but the ordering
967    /// on the borrowed form *must* match the ordering on the key type.
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// use std::collections::BTreeMap;
973    ///
974    /// let mut map = BTreeMap::new();
975    /// map.insert(1, "a");
976    /// assert_eq!(map.contains_key(&1), true);
977    /// assert_eq!(map.contains_key(&2), false);
978    /// ```
979    #[stable(feature = "rust1", since = "1.0.0")]
980    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
981    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
982    where
983        K: Borrow<Q> + Ord,
984        Q: Ord,
985    {
986        self.get(key).is_some()
987    }
988
989    /// Returns a mutable reference to the value corresponding to the key.
990    ///
991    /// The key may be any borrowed form of the map's key type, but the ordering
992    /// on the borrowed form *must* match the ordering on the key type.
993    ///
994    /// # Examples
995    ///
996    /// ```
997    /// use std::collections::BTreeMap;
998    ///
999    /// let mut map = BTreeMap::new();
1000    /// map.insert(1, "a");
1001    /// if let Some(x) = map.get_mut(&1) {
1002    ///     *x = "b";
1003    /// }
1004    /// assert_eq!(map[&1], "b");
1005    /// ```
1006    // See `get` for implementation notes, this is basically a copy-paste with mut's added
1007    #[stable(feature = "rust1", since = "1.0.0")]
1008    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1009    where
1010        K: Borrow<Q> + Ord,
1011        Q: Ord,
1012    {
1013        let root_node = self.root.as_mut()?.borrow_mut();
1014        match root_node.search_tree(key) {
1015            Found(handle) => Some(handle.into_val_mut()),
1016            GoDown(_) => None,
1017        }
1018    }
1019
1020    /// Inserts a key-value pair into the map.
1021    ///
1022    /// If the map did not have this key present, `None` is returned.
1023    ///
1024    /// If the map did have this key present, the value is updated, and the old
1025    /// value is returned. The key is not updated, though; this matters for
1026    /// types that can be `==` without being identical. See the [module-level
1027    /// documentation] for more.
1028    ///
1029    /// [module-level documentation]: index.html#insert-and-complex-keys
1030    ///
1031    /// # Examples
1032    ///
1033    /// ```
1034    /// use std::collections::BTreeMap;
1035    ///
1036    /// let mut map = BTreeMap::new();
1037    /// assert_eq!(map.insert(37, "a"), None);
1038    /// assert_eq!(map.is_empty(), false);
1039    ///
1040    /// map.insert(37, "b");
1041    /// assert_eq!(map.insert(37, "c"), Some("b"));
1042    /// assert_eq!(map[&37], "c");
1043    /// ```
1044    #[stable(feature = "rust1", since = "1.0.0")]
1045    #[rustc_confusables("push", "put", "set")]
1046    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1047    pub fn insert(&mut self, key: K, value: V) -> Option<V>
1048    where
1049        K: Ord,
1050    {
1051        match self.entry(key) {
1052            Occupied(mut entry) => Some(entry.insert(value)),
1053            Vacant(entry) => {
1054                entry.insert(value);
1055                None
1056            }
1057        }
1058    }
1059
1060    /// Tries to insert a key-value pair into the map, and returns
1061    /// a mutable reference to the value in the entry.
1062    ///
1063    /// If the map already had this key present, nothing is updated, and
1064    /// an error containing the occupied entry, key, and the value is returned.
1065    ///
1066    /// # Examples
1067    ///
1068    /// ```
1069    /// #![feature(map_try_insert)]
1070    ///
1071    /// use std::collections::BTreeMap;
1072    ///
1073    /// let mut map = BTreeMap::new();
1074    /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1075    ///
1076    /// let err = map.try_insert(37, "b").unwrap_err();
1077    /// assert_eq!(err.entry.key(), &37);
1078    /// assert_eq!(err.entry.get(), &"a");
1079    /// assert_eq!(err.key, 37);
1080    /// assert_eq!(err.value, "b");
1081    /// ```
1082    #[unstable(feature = "map_try_insert", issue = "82766")]
1083    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
1084    where
1085        K: Ord,
1086    {
1087        let (map, dormant_map) = DormantMutRef::new(self);
1088        let handle = match map.root {
1089            Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1090                Found(handle) => {
1091                    let entry = OccupiedEntry {
1092                        handle,
1093                        dormant_map,
1094                        alloc: (*map.alloc).clone(),
1095                        _marker: PhantomData,
1096                    };
1097                    return Err(OccupiedError { entry, key, value });
1098                }
1099                GoDown(handle) => Some(handle),
1100            },
1101            None => None,
1102        };
1103        let entry = VacantEntry {
1104            key,
1105            handle,
1106            dormant_map,
1107            alloc: (*map.alloc).clone(),
1108            _marker: PhantomData,
1109        };
1110        Ok(entry.insert(value))
1111    }
1112
1113    /// Removes a key from the map, returning the value at the key if the key
1114    /// was previously in the map.
1115    ///
1116    /// The key may be any borrowed form of the map's key type, but the ordering
1117    /// on the borrowed form *must* match the ordering on the key type.
1118    ///
1119    /// # Examples
1120    ///
1121    /// ```
1122    /// use std::collections::BTreeMap;
1123    ///
1124    /// let mut map = BTreeMap::new();
1125    /// map.insert(1, "a");
1126    /// assert_eq!(map.remove(&1), Some("a"));
1127    /// assert_eq!(map.remove(&1), None);
1128    /// ```
1129    #[stable(feature = "rust1", since = "1.0.0")]
1130    #[rustc_confusables("delete", "take")]
1131    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1132    where
1133        K: Borrow<Q> + Ord,
1134        Q: Ord,
1135    {
1136        self.remove_entry(key).map(|(_, v)| v)
1137    }
1138
1139    /// Removes a key from the map, returning the stored key and value if the key
1140    /// was previously in the map.
1141    ///
1142    /// The key may be any borrowed form of the map's key type, but the ordering
1143    /// on the borrowed form *must* match the ordering on the key type.
1144    ///
1145    /// # Examples
1146    ///
1147    /// ```
1148    /// use std::collections::BTreeMap;
1149    ///
1150    /// let mut map = BTreeMap::new();
1151    /// map.insert(1, "a");
1152    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1153    /// assert_eq!(map.remove_entry(&1), None);
1154    /// ```
1155    #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1156    pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1157    where
1158        K: Borrow<Q> + Ord,
1159        Q: Ord,
1160    {
1161        let (map, dormant_map) = DormantMutRef::new(self);
1162        let root_node = map.root.as_mut()?.borrow_mut();
1163        match root_node.search_tree(key) {
1164            Found(handle) => Some(
1165                OccupiedEntry {
1166                    handle,
1167                    dormant_map,
1168                    alloc: (*map.alloc).clone(),
1169                    _marker: PhantomData,
1170                }
1171                .remove_entry(),
1172            ),
1173            GoDown(_) => None,
1174        }
1175    }
1176
1177    /// Retains only the elements specified by the predicate.
1178    ///
1179    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1180    /// The elements are visited in ascending key order.
1181    ///
1182    /// # Examples
1183    ///
1184    /// ```
1185    /// use std::collections::BTreeMap;
1186    ///
1187    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1188    /// // Keep only the elements with even-numbered keys.
1189    /// map.retain(|&k, _| k % 2 == 0);
1190    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1191    /// ```
1192    #[inline]
1193    #[stable(feature = "btree_retain", since = "1.53.0")]
1194    pub fn retain<F>(&mut self, mut f: F)
1195    where
1196        K: Ord,
1197        F: FnMut(&K, &mut V) -> bool,
1198    {
1199        self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1200    }
1201
1202    /// Moves all elements from `other` into `self`, leaving `other` empty.
1203    ///
1204    /// If a key from `other` is already present in `self`, the respective
1205    /// value from `self` will be overwritten with the respective value from `other`.
1206    /// Similar to [`insert`], though, the key is not overwritten,
1207    /// which matters for types that can be `==` without being identical.
1208    ///
1209    /// [`insert`]: BTreeMap::insert
1210    ///
1211    /// # Examples
1212    ///
1213    /// ```
1214    /// use std::collections::BTreeMap;
1215    ///
1216    /// let mut a = BTreeMap::new();
1217    /// a.insert(1, "a");
1218    /// a.insert(2, "b");
1219    /// a.insert(3, "c"); // Note: Key (3) also present in b.
1220    ///
1221    /// let mut b = BTreeMap::new();
1222    /// b.insert(3, "d"); // Note: Key (3) also present in a.
1223    /// b.insert(4, "e");
1224    /// b.insert(5, "f");
1225    ///
1226    /// a.append(&mut b);
1227    ///
1228    /// assert_eq!(a.len(), 5);
1229    /// assert_eq!(b.len(), 0);
1230    ///
1231    /// assert_eq!(a[&1], "a");
1232    /// assert_eq!(a[&2], "b");
1233    /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1234    /// assert_eq!(a[&4], "e");
1235    /// assert_eq!(a[&5], "f");
1236    /// ```
1237    #[stable(feature = "btree_append", since = "1.11.0")]
1238    pub fn append(&mut self, other: &mut Self)
1239    where
1240        K: Ord,
1241        A: Clone,
1242    {
1243        let other = mem::replace(other, Self::new_in((*self.alloc).clone()));
1244        self.merge(other, |_key, _self_val, other_val| other_val);
1245    }
1246
1247    /// Moves all elements from `other` into `self`, leaving `other` empty.
1248    ///
1249    /// If a key from `other` is already present in `self`, then the `conflict`
1250    /// closure is used to return a value to `self`. The `conflict`
1251    /// closure takes in a borrow of `self`'s key, `self`'s value, and `other`'s value
1252    /// in that order.
1253    ///
1254    /// An example of why one might use this method over [`append`]
1255    /// is to combine `self`'s value with `other`'s value when their keys conflict.
1256    ///
1257    /// Similar to [`insert`], though, the key is not overwritten,
1258    /// which matters for types that can be `==` without being identical.
1259    ///
1260    /// [`insert`]: BTreeMap::insert
1261    /// [`append`]: BTreeMap::append
1262    ///
1263    /// # Examples
1264    ///
1265    /// ```
1266    /// #![feature(btree_merge)]
1267    /// use std::collections::BTreeMap;
1268    ///
1269    /// let mut a = BTreeMap::new();
1270    /// a.insert(1, String::from("a"));
1271    /// a.insert(2, String::from("b"));
1272    /// a.insert(3, String::from("c")); // Note: Key (3) also present in b.
1273    ///
1274    /// let mut b = BTreeMap::new();
1275    /// b.insert(3, String::from("d")); // Note: Key (3) also present in a.
1276    /// b.insert(4, String::from("e"));
1277    /// b.insert(5, String::from("f"));
1278    ///
1279    /// // concatenate a's value and b's value
1280    /// a.merge(b, |_, a_val, b_val| {
1281    ///     format!("{a_val}{b_val}")
1282    /// });
1283    ///
1284    /// assert_eq!(a.len(), 5); // all of b's keys in a
1285    ///
1286    /// assert_eq!(a[&1], "a");
1287    /// assert_eq!(a[&2], "b");
1288    /// assert_eq!(a[&3], "cd"); // Note: "c" has been combined with "d".
1289    /// assert_eq!(a[&4], "e");
1290    /// assert_eq!(a[&5], "f");
1291    /// ```
1292    #[unstable(feature = "btree_merge", issue = "152152")]
1293    pub fn merge(&mut self, mut other: Self, mut conflict: impl FnMut(&K, V, V) -> V)
1294    where
1295        K: Ord,
1296        A: Clone,
1297    {
1298        // Do we have to append anything at all?
1299        if other.is_empty() {
1300            return;
1301        }
1302
1303        // We can just swap `self` and `other` if `self` is empty.
1304        if self.is_empty() {
1305            mem::swap(self, &mut other);
1306            return;
1307        }
1308
1309        let mut other_iter = other.into_iter();
1310        let (first_other_key, first_other_val) = other_iter.next().unwrap();
1311
1312        // find the first gap that has the smallest key greater than or equal to
1313        // the first key from other
1314        let mut self_cursor = self.lower_bound_mut(Bound::Included(&first_other_key));
1315
1316        if let Some((self_key, _)) = self_cursor.peek_next() {
1317            match K::cmp(self_key, &first_other_key) {
1318                Ordering::Equal => {
1319                    // if `f` unwinds, the next entry is already removed leaving
1320                    // the tree in valid state.
1321                    // FIXME: Once `MaybeDangling` is implemented, we can optimize
1322                    // this through using a drop handler and transmutating CursorMutKey<K, V>
1323                    // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1324                    if let Some((k, v)) = self_cursor.remove_next() {
1325                        let v = conflict(&k, v, first_other_val);
1326                        // SAFETY: we remove the K, V out of the next entry,
1327                        // apply 'f' to get a new (K, V), and insert it back
1328                        // into the next entry that the cursor is pointing at
1329                        unsafe { self_cursor.insert_after_unchecked(k, v) };
1330                    }
1331                }
1332                Ordering::Greater =>
1333                // SAFETY: we know our other_key's ordering is less than self_key,
1334                // so inserting before will guarantee sorted order
1335                unsafe {
1336                    self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1337                },
1338                Ordering::Less => {
1339                    unreachable!("Cursor's peek_next should return None.");
1340                }
1341            }
1342        } else {
1343            // SAFETY: reaching here means our cursor is at the end
1344            // self BTreeMap so we just insert other_key here
1345            unsafe {
1346                self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1347            }
1348        }
1349
1350        for (other_key, other_val) in other_iter {
1351            loop {
1352                if let Some((self_key, _)) = self_cursor.peek_next() {
1353                    match K::cmp(self_key, &other_key) {
1354                        Ordering::Equal => {
1355                            // if `f` unwinds, the next entry is already removed leaving
1356                            // the tree in valid state.
1357                            // FIXME: Once `MaybeDangling` is implemented, we can optimize
1358                            // this through using a drop handler and transmutating CursorMutKey<K, V>
1359                            // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1360                            if let Some((k, v)) = self_cursor.remove_next() {
1361                                let v = conflict(&k, v, other_val);
1362                                // SAFETY: we remove the K, V out of the next entry,
1363                                // apply 'f' to get a new (K, V), and insert it back
1364                                // into the next entry that the cursor is pointing at
1365                                unsafe { self_cursor.insert_after_unchecked(k, v) };
1366                            }
1367                            break;
1368                        }
1369                        Ordering::Greater => {
1370                            // SAFETY: we know our self_key's ordering is greater than other_key,
1371                            // so inserting before will guarantee sorted order
1372                            unsafe {
1373                                self_cursor.insert_before_unchecked(other_key, other_val);
1374                            }
1375                            break;
1376                        }
1377                        Ordering::Less => {
1378                            // FIXME: instead of doing a linear search here,
1379                            // this can be optimized to search the tree by starting
1380                            // from self_cursor and going towards the root and then
1381                            // back down to the proper node -- that should probably
1382                            // be a new method on Cursor*.
1383                            self_cursor.next();
1384                        }
1385                    }
1386                } else {
1387                    // FIXME: If we get here, that means all of other's keys are greater than
1388                    // self's keys. For performance, this should really do a bulk insertion of items
1389                    // from other_iter into the end of self `BTreeMap`. Maybe this should be
1390                    // a method for Cursor*?
1391
1392                    // SAFETY: reaching here means our cursor is at the end
1393                    // self BTreeMap so we just insert other_key here
1394                    unsafe {
1395                        self_cursor.insert_before_unchecked(other_key, other_val);
1396                    }
1397                    break;
1398                }
1399            }
1400        }
1401    }
1402
1403    /// Constructs a double-ended iterator over a sub-range of elements in the map.
1404    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1405    /// yield elements from min (inclusive) to max (exclusive).
1406    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1407    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1408    /// range from 4 to 10.
1409    ///
1410    /// # Panics
1411    ///
1412    /// Panics if range `start > end`.
1413    /// Panics if range `start == end` and both bounds are `Excluded`.
1414    ///
1415    /// # Examples
1416    ///
1417    /// ```
1418    /// use std::collections::BTreeMap;
1419    /// use std::ops::Bound::Included;
1420    ///
1421    /// let mut map = BTreeMap::new();
1422    /// map.insert(3, "a");
1423    /// map.insert(5, "b");
1424    /// map.insert(8, "c");
1425    /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1426    ///     println!("{key}: {value}");
1427    /// }
1428    /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1429    /// ```
1430    #[stable(feature = "btree_range", since = "1.17.0")]
1431    pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1432    where
1433        T: Ord,
1434        K: Borrow<T> + Ord,
1435        R: RangeBounds<T>,
1436    {
1437        if let Some(root) = &self.root {
1438            Range { inner: root.reborrow().range_search(range) }
1439        } else {
1440            Range { inner: LeafRange::none() }
1441        }
1442    }
1443
1444    /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1445    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1446    /// yield elements from min (inclusive) to max (exclusive).
1447    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1448    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1449    /// range from 4 to 10.
1450    ///
1451    /// # Panics
1452    ///
1453    /// Panics if range `start > end`.
1454    /// Panics if range `start == end` and both bounds are `Excluded`.
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```
1459    /// use std::collections::BTreeMap;
1460    ///
1461    /// let mut map: BTreeMap<&str, i32> =
1462    ///     [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1463    /// for (_, balance) in map.range_mut("B".."Cheryl") {
1464    ///     *balance += 100;
1465    /// }
1466    /// for (name, balance) in &map {
1467    ///     println!("{name} => {balance}");
1468    /// }
1469    /// ```
1470    #[stable(feature = "btree_range", since = "1.17.0")]
1471    pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1472    where
1473        T: Ord,
1474        K: Borrow<T> + Ord,
1475        R: RangeBounds<T>,
1476    {
1477        if let Some(root) = &mut self.root {
1478            RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1479        } else {
1480            RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1481        }
1482    }
1483
1484    /// Gets the given key's corresponding entry in the map for in-place manipulation.
1485    ///
1486    /// # Examples
1487    ///
1488    /// ```
1489    /// use std::collections::BTreeMap;
1490    ///
1491    /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1492    ///
1493    /// // count the number of occurrences of letters in the vec
1494    /// for x in ["a", "b", "a", "c", "a", "b"] {
1495    ///     count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1496    /// }
1497    ///
1498    /// assert_eq!(count["a"], 3);
1499    /// assert_eq!(count["b"], 2);
1500    /// assert_eq!(count["c"], 1);
1501    /// ```
1502    #[stable(feature = "rust1", since = "1.0.0")]
1503    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1504    where
1505        K: Ord,
1506    {
1507        let (map, dormant_map) = DormantMutRef::new(self);
1508        match map.root {
1509            None => Vacant(VacantEntry {
1510                key,
1511                handle: None,
1512                dormant_map,
1513                alloc: (*map.alloc).clone(),
1514                _marker: PhantomData,
1515            }),
1516            Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1517                Found(handle) => Occupied(OccupiedEntry {
1518                    handle,
1519                    dormant_map,
1520                    alloc: (*map.alloc).clone(),
1521                    _marker: PhantomData,
1522                }),
1523                GoDown(handle) => Vacant(VacantEntry {
1524                    key,
1525                    handle: Some(handle),
1526                    dormant_map,
1527                    alloc: (*map.alloc).clone(),
1528                    _marker: PhantomData,
1529                }),
1530            },
1531        }
1532    }
1533
1534    /// Splits the collection into two at the given key. Returns everything after the given key,
1535    /// including the key. If the key is not present, the split will occur at the nearest
1536    /// greater key, or return an empty map if no such key exists.
1537    ///
1538    /// # Examples
1539    ///
1540    /// ```
1541    /// use std::collections::BTreeMap;
1542    ///
1543    /// let mut a = BTreeMap::new();
1544    /// a.insert(1, "a");
1545    /// a.insert(2, "b");
1546    /// a.insert(3, "c");
1547    /// a.insert(17, "d");
1548    /// a.insert(41, "e");
1549    ///
1550    /// let b = a.split_off(&3);
1551    ///
1552    /// assert_eq!(a.len(), 2);
1553    /// assert_eq!(b.len(), 3);
1554    ///
1555    /// assert_eq!(a[&1], "a");
1556    /// assert_eq!(a[&2], "b");
1557    ///
1558    /// assert_eq!(b[&3], "c");
1559    /// assert_eq!(b[&17], "d");
1560    /// assert_eq!(b[&41], "e");
1561    /// ```
1562    #[stable(feature = "btree_split_off", since = "1.11.0")]
1563    pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1564    where
1565        K: Borrow<Q> + Ord,
1566        A: Clone,
1567    {
1568        if self.is_empty() {
1569            return Self::new_in((*self.alloc).clone());
1570        }
1571
1572        let total_num = self.len();
1573        let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1574
1575        let right_root = left_root.split_off(key, (*self.alloc).clone());
1576
1577        let (new_left_len, right_len) = Root::calc_split_length(total_num, left_root, &right_root);
1578        self.length = new_left_len;
1579
1580        BTreeMap {
1581            root: Some(right_root),
1582            length: right_len,
1583            alloc: self.alloc.clone(),
1584            _marker: PhantomData,
1585        }
1586    }
1587
1588    /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1589    /// ascending key order and uses a closure to determine if an element
1590    /// should be removed.
1591    ///
1592    /// If the closure returns `true`, the element is removed from the map and
1593    /// yielded. If the closure returns `false`, or panics, the element remains
1594    /// in the map and will not be yielded.
1595    ///
1596    /// The iterator also lets you mutate the value of each element in the
1597    /// closure, regardless of whether you choose to keep or remove it.
1598    ///
1599    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1600    /// or the iteration short-circuits, then the remaining elements will be retained.
1601    /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1602    /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1603    ///
1604    /// [`retain`]: BTreeMap::retain
1605    ///
1606    /// # Examples
1607    ///
1608    /// ```
1609    /// use std::collections::BTreeMap;
1610    ///
1611    /// // Splitting a map into even and odd keys, reusing the original map:
1612    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1613    /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1614    /// let odds = map;
1615    /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1616    /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1617    ///
1618    /// // Splitting a map into low and high halves, reusing the original map:
1619    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1620    /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1621    /// let high = map;
1622    /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1623    /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1624    /// ```
1625    #[stable(feature = "btree_extract_if", since = "1.91.0")]
1626    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1627    where
1628        K: Ord,
1629        R: RangeBounds<K>,
1630        F: FnMut(&K, &mut V) -> bool,
1631    {
1632        let (inner, alloc) = self.extract_if_inner(range);
1633        ExtractIf { pred, inner, alloc }
1634    }
1635
1636    pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1637    where
1638        K: Ord,
1639        R: RangeBounds<K>,
1640    {
1641        if let Some(root) = self.root.as_mut() {
1642            let (root, dormant_root) = DormantMutRef::new(root);
1643            let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1644            (
1645                ExtractIfInner {
1646                    length: &mut self.length,
1647                    dormant_root: Some(dormant_root),
1648                    cur_leaf_edge: Some(first),
1649                    range,
1650                },
1651                (*self.alloc).clone(),
1652            )
1653        } else {
1654            (
1655                ExtractIfInner {
1656                    length: &mut self.length,
1657                    dormant_root: None,
1658                    cur_leaf_edge: None,
1659                    range,
1660                },
1661                (*self.alloc).clone(),
1662            )
1663        }
1664    }
1665
1666    /// Creates a consuming iterator visiting all the keys, in sorted order.
1667    /// The map cannot be used after calling this.
1668    /// The iterator element type is `K`.
1669    ///
1670    /// # Examples
1671    ///
1672    /// ```
1673    /// use std::collections::BTreeMap;
1674    ///
1675    /// let mut a = BTreeMap::new();
1676    /// a.insert(2, "b");
1677    /// a.insert(1, "a");
1678    ///
1679    /// let keys: Vec<i32> = a.into_keys().collect();
1680    /// assert_eq!(keys, [1, 2]);
1681    /// ```
1682    #[inline]
1683    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1684    pub fn into_keys(self) -> IntoKeys<K, V, A> {
1685        IntoKeys { inner: self.into_iter() }
1686    }
1687
1688    /// Creates a consuming iterator visiting all the values, in order by key.
1689    /// The map cannot be used after calling this.
1690    /// The iterator element type is `V`.
1691    ///
1692    /// # Examples
1693    ///
1694    /// ```
1695    /// use std::collections::BTreeMap;
1696    ///
1697    /// let mut a = BTreeMap::new();
1698    /// a.insert(1, "hello");
1699    /// a.insert(2, "goodbye");
1700    ///
1701    /// let values: Vec<&str> = a.into_values().collect();
1702    /// assert_eq!(values, ["hello", "goodbye"]);
1703    /// ```
1704    #[inline]
1705    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1706    pub fn into_values(self) -> IntoValues<K, V, A> {
1707        IntoValues { inner: self.into_iter() }
1708    }
1709
1710    /// Makes a `BTreeMap` from a sorted iterator.
1711    pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1712    where
1713        K: Ord,
1714        I: IntoIterator<Item = (K, V)>,
1715    {
1716        let mut root = Root::new(alloc.clone());
1717        let mut length = 0;
1718        root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1719        BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1720    }
1721}
1722
1723#[stable(feature = "rust1", since = "1.0.0")]
1724impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a BTreeMap<K, V, A> {
1725    type Item = (&'a K, &'a V);
1726    type IntoIter = Iter<'a, K, V>;
1727
1728    fn into_iter(self) -> Iter<'a, K, V> {
1729        self.iter()
1730    }
1731}
1732
1733#[stable(feature = "rust1", since = "1.0.0")]
1734impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1735    type Item = (&'a K, &'a V);
1736
1737    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1738        if self.length == 0 {
1739            None
1740        } else {
1741            self.length -= 1;
1742            // SAFETY: Ensured by check.
1743            Some(unsafe { self.range.next_unchecked() })
1744        }
1745    }
1746
1747    fn size_hint(&self) -> (usize, Option<usize>) {
1748        (self.length, Some(self.length))
1749    }
1750
1751    fn last(mut self) -> Option<(&'a K, &'a V)> {
1752        self.next_back()
1753    }
1754
1755    fn min(mut self) -> Option<(&'a K, &'a V)>
1756    where
1757        (&'a K, &'a V): Ord,
1758    {
1759        self.next()
1760    }
1761
1762    fn max(mut self) -> Option<(&'a K, &'a V)>
1763    where
1764        (&'a K, &'a V): Ord,
1765    {
1766        self.next_back()
1767    }
1768}
1769
1770#[stable(feature = "fused", since = "1.26.0")]
1771impl<K, V> FusedIterator for Iter<'_, K, V> {}
1772
1773#[stable(feature = "rust1", since = "1.0.0")]
1774impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1775    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1776        if self.length == 0 {
1777            None
1778        } else {
1779            self.length -= 1;
1780            // SAFETY: Ensured by check.
1781            Some(unsafe { self.range.next_back_unchecked() })
1782        }
1783    }
1784}
1785
1786#[stable(feature = "rust1", since = "1.0.0")]
1787impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1788    fn len(&self) -> usize {
1789        self.length
1790    }
1791}
1792
1793#[unstable(feature = "trusted_len", issue = "37572")]
1794unsafe impl<K, V> TrustedLen for Iter<'_, K, V> {}
1795
1796#[stable(feature = "rust1", since = "1.0.0")]
1797impl<K, V> Clone for Iter<'_, K, V> {
1798    fn clone(&self) -> Self {
1799        Iter { range: self.range.clone(), length: self.length }
1800    }
1801}
1802
1803#[stable(feature = "rust1", since = "1.0.0")]
1804impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1805    type Item = (&'a K, &'a mut V);
1806    type IntoIter = IterMut<'a, K, V>;
1807
1808    fn into_iter(self) -> IterMut<'a, K, V> {
1809        self.iter_mut()
1810    }
1811}
1812
1813#[stable(feature = "rust1", since = "1.0.0")]
1814impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1815    type Item = (&'a K, &'a mut V);
1816
1817    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1818        if self.length == 0 {
1819            None
1820        } else {
1821            self.length -= 1;
1822            // SAFETY: Ensured by check.
1823            Some(unsafe { self.range.next_unchecked() })
1824        }
1825    }
1826
1827    fn size_hint(&self) -> (usize, Option<usize>) {
1828        (self.length, Some(self.length))
1829    }
1830
1831    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1832        self.next_back()
1833    }
1834
1835    fn min(mut self) -> Option<(&'a K, &'a mut V)>
1836    where
1837        (&'a K, &'a mut V): Ord,
1838    {
1839        self.next()
1840    }
1841
1842    fn max(mut self) -> Option<(&'a K, &'a mut V)>
1843    where
1844        (&'a K, &'a mut V): Ord,
1845    {
1846        self.next_back()
1847    }
1848}
1849
1850#[stable(feature = "rust1", since = "1.0.0")]
1851impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1852    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1853        if self.length == 0 {
1854            None
1855        } else {
1856            self.length -= 1;
1857            // SAFETY: Ensured by check.
1858            Some(unsafe { self.range.next_back_unchecked() })
1859        }
1860    }
1861}
1862
1863#[stable(feature = "rust1", since = "1.0.0")]
1864impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1865    fn len(&self) -> usize {
1866        self.length
1867    }
1868}
1869
1870#[unstable(feature = "trusted_len", issue = "37572")]
1871unsafe impl<K, V> TrustedLen for IterMut<'_, K, V> {}
1872
1873#[stable(feature = "fused", since = "1.26.0")]
1874impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1875
1876impl<'a, K, V> IterMut<'a, K, V> {
1877    /// Returns an iterator of references over the remaining items.
1878    #[inline]
1879    pub(super) fn iter(&self) -> Iter<'_, K, V> {
1880        Iter { range: self.range.reborrow(), length: self.length }
1881    }
1882}
1883
1884#[stable(feature = "rust1", since = "1.0.0")]
1885impl<K, V, A: AllocatorClone> IntoIterator for BTreeMap<K, V, A> {
1886    type Item = (K, V);
1887    type IntoIter = IntoIter<K, V, A>;
1888
1889    /// Gets an owning iterator over the entries of the map, sorted by key.
1890    fn into_iter(self) -> IntoIter<K, V, A> {
1891        let mut me = ManuallyDrop::new(self);
1892        if let Some(root) = me.root.take() {
1893            let full_range = root.into_dying().full_range();
1894
1895            IntoIter {
1896                range: full_range,
1897                length: me.length,
1898                // ignore-tidy-undocumented-unsafe
1899                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1900            }
1901        } else {
1902            IntoIter {
1903                range: LazyLeafRange::none(),
1904                length: 0,
1905                // ignore-tidy-undocumented-unsafe
1906                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1907            }
1908        }
1909    }
1910}
1911
1912#[stable(feature = "btree_drop", since = "1.7.0")]
1913impl<K, V, A: AllocatorClone> Drop for IntoIter<K, V, A> {
1914    fn drop(&mut self) {
1915        struct DropGuard<'a, K, V, A: AllocatorClone>(&'a mut IntoIter<K, V, A>);
1916
1917        impl<'a, K, V, A: AllocatorClone> Drop for DropGuard<'a, K, V, A> {
1918            fn drop(&mut self) {
1919                // Continue the same loop we perform below. This only runs when unwinding, so we
1920                // don't have to care about panics this time (they'll abort).
1921                while let Some(kv) = self.0.dying_next() {
1922                    // SAFETY: we consume the dying handle immediately.
1923                    unsafe { kv.drop_key_val() };
1924                }
1925            }
1926        }
1927
1928        while let Some(kv) = self.dying_next() {
1929            let guard = DropGuard(self);
1930            // SAFETY: we don't touch the tree before consuming the dying handle.
1931            unsafe { kv.drop_key_val() };
1932            mem::forget(guard);
1933        }
1934    }
1935}
1936
1937impl<K, V, A: AllocatorClone> IntoIter<K, V, A> {
1938    /// Core of a `next` method returning a dying KV handle,
1939    /// invalidated by further calls to this function and some others.
1940    fn dying_next(
1941        &mut self,
1942    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1943        if self.length == 0 {
1944            self.range.deallocating_end(self.alloc.clone());
1945            None
1946        } else {
1947            self.length -= 1;
1948            // ignore-tidy-undocumented-unsafe
1949            Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1950        }
1951    }
1952
1953    /// Core of a `next_back` method returning a dying KV handle,
1954    /// invalidated by further calls to this function and some others.
1955    fn dying_next_back(
1956        &mut self,
1957    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1958        if self.length == 0 {
1959            self.range.deallocating_end(self.alloc.clone());
1960            None
1961        } else {
1962            self.length -= 1;
1963            // ignore-tidy-undocumented-unsafe
1964            Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1965        }
1966    }
1967}
1968
1969#[stable(feature = "rust1", since = "1.0.0")]
1970impl<K, V, A: AllocatorClone> Iterator for IntoIter<K, V, A> {
1971    type Item = (K, V);
1972
1973    fn next(&mut self) -> Option<(K, V)> {
1974        // SAFETY: we consume the dying handle immediately.
1975        self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1976    }
1977
1978    fn size_hint(&self) -> (usize, Option<usize>) {
1979        (self.length, Some(self.length))
1980    }
1981}
1982
1983#[stable(feature = "rust1", since = "1.0.0")]
1984impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoIter<K, V, A> {
1985    fn next_back(&mut self) -> Option<(K, V)> {
1986        // SAFETY: we consume the dying handle immediately.
1987        self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1988    }
1989}
1990
1991#[stable(feature = "rust1", since = "1.0.0")]
1992impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoIter<K, V, A> {
1993    fn len(&self) -> usize {
1994        self.length
1995    }
1996}
1997
1998#[unstable(feature = "trusted_len", issue = "37572")]
1999unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoIter<K, V, A> {}
2000
2001#[stable(feature = "fused", since = "1.26.0")]
2002impl<K, V, A: AllocatorClone> FusedIterator for IntoIter<K, V, A> {}
2003
2004#[stable(feature = "rust1", since = "1.0.0")]
2005impl<'a, K, V> Iterator for Keys<'a, K, V> {
2006    type Item = &'a K;
2007
2008    fn next(&mut self) -> Option<&'a K> {
2009        self.inner.next().map(|(k, _)| k)
2010    }
2011
2012    fn size_hint(&self) -> (usize, Option<usize>) {
2013        self.inner.size_hint()
2014    }
2015
2016    fn last(mut self) -> Option<&'a K> {
2017        self.next_back()
2018    }
2019
2020    fn min(mut self) -> Option<&'a K>
2021    where
2022        &'a K: Ord,
2023    {
2024        self.next()
2025    }
2026
2027    fn max(mut self) -> Option<&'a K>
2028    where
2029        &'a K: Ord,
2030    {
2031        self.next_back()
2032    }
2033}
2034
2035#[stable(feature = "rust1", since = "1.0.0")]
2036impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
2037    fn next_back(&mut self) -> Option<&'a K> {
2038        self.inner.next_back().map(|(k, _)| k)
2039    }
2040}
2041
2042#[stable(feature = "rust1", since = "1.0.0")]
2043impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2044    fn len(&self) -> usize {
2045        self.inner.len()
2046    }
2047}
2048
2049#[unstable(feature = "trusted_len", issue = "37572")]
2050unsafe impl<K, V> TrustedLen for Keys<'_, K, V> {}
2051
2052#[stable(feature = "fused", since = "1.26.0")]
2053impl<K, V> FusedIterator for Keys<'_, K, V> {}
2054
2055#[stable(feature = "rust1", since = "1.0.0")]
2056impl<K, V> Clone for Keys<'_, K, V> {
2057    fn clone(&self) -> Self {
2058        Keys { inner: self.inner.clone() }
2059    }
2060}
2061
2062#[stable(feature = "default_iters", since = "1.70.0")]
2063impl<K, V> Default for Keys<'_, K, V> {
2064    /// Creates an empty `btree_map::Keys`.
2065    ///
2066    /// ```
2067    /// # use std::collections::btree_map;
2068    /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
2069    /// assert_eq!(iter.len(), 0);
2070    /// ```
2071    fn default() -> Self {
2072        Keys { inner: Default::default() }
2073    }
2074}
2075
2076#[stable(feature = "rust1", since = "1.0.0")]
2077impl<'a, K, V> Iterator for Values<'a, K, V> {
2078    type Item = &'a V;
2079
2080    fn next(&mut self) -> Option<&'a V> {
2081        self.inner.next().map(|(_, v)| v)
2082    }
2083
2084    fn size_hint(&self) -> (usize, Option<usize>) {
2085        self.inner.size_hint()
2086    }
2087
2088    fn last(mut self) -> Option<&'a V> {
2089        self.next_back()
2090    }
2091}
2092
2093#[stable(feature = "rust1", since = "1.0.0")]
2094impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
2095    fn next_back(&mut self) -> Option<&'a V> {
2096        self.inner.next_back().map(|(_, v)| v)
2097    }
2098}
2099
2100#[stable(feature = "rust1", since = "1.0.0")]
2101impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2102    fn len(&self) -> usize {
2103        self.inner.len()
2104    }
2105}
2106
2107#[unstable(feature = "trusted_len", issue = "37572")]
2108unsafe impl<K, V> TrustedLen for Values<'_, K, V> {}
2109
2110#[stable(feature = "fused", since = "1.26.0")]
2111impl<K, V> FusedIterator for Values<'_, K, V> {}
2112
2113#[stable(feature = "rust1", since = "1.0.0")]
2114impl<K, V> Clone for Values<'_, K, V> {
2115    fn clone(&self) -> Self {
2116        Values { inner: self.inner.clone() }
2117    }
2118}
2119
2120#[stable(feature = "default_iters", since = "1.70.0")]
2121impl<K, V> Default for Values<'_, K, V> {
2122    /// Creates an empty `btree_map::Values`.
2123    ///
2124    /// ```
2125    /// # use std::collections::btree_map;
2126    /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
2127    /// assert_eq!(iter.len(), 0);
2128    /// ```
2129    fn default() -> Self {
2130        Values { inner: Default::default() }
2131    }
2132}
2133
2134/// This `struct` is created by the [`extract_if`] method on [`BTreeMap`].
2135///
2136/// [`extract_if`]: BTreeMap::extract_if
2137#[stable(feature = "btree_extract_if", since = "1.91.0")]
2138#[must_use = "iterators are lazy and do nothing unless consumed; \
2139    use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
2140pub struct ExtractIf<
2141    'a,
2142    K,
2143    V,
2144    R,
2145    F,
2146    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global,
2147> {
2148    pred: F,
2149    inner: ExtractIfInner<'a, K, V, R>,
2150    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
2151    alloc: A,
2152}
2153
2154/// Most of the implementation of ExtractIf are generic over the type
2155/// of the predicate, thus also serving for BTreeSet::ExtractIf.
2156pub(super) struct ExtractIfInner<'a, K, V, R> {
2157    /// Reference to the length field in the borrowed map, updated live.
2158    length: &'a mut usize,
2159    /// Buried reference to the root field in the borrowed map.
2160    /// Wrapped in `Option` to allow drop handler to `take` it.
2161    dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
2162    /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
2163    /// Empty if the map has no root, if iteration went beyond the last leaf edge,
2164    /// or if a panic occurred in the predicate.
2165    cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2166    /// Range over which iteration was requested.  We don't need the left side, but we
2167    /// can't extract the right side without requiring K: Clone.
2168    range: R,
2169}
2170
2171#[stable(feature = "btree_extract_if", since = "1.91.0")]
2172impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
2173where
2174    K: fmt::Debug,
2175    V: fmt::Debug,
2176    A: AllocatorClone,
2177{
2178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2179        f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
2180    }
2181}
2182
2183#[stable(feature = "btree_extract_if", since = "1.91.0")]
2184impl<K, V, R, F, A: AllocatorClone> Iterator for ExtractIf<'_, K, V, R, F, A>
2185where
2186    K: PartialOrd,
2187    R: RangeBounds<K>,
2188    F: FnMut(&K, &mut V) -> bool,
2189{
2190    type Item = (K, V);
2191
2192    fn next(&mut self) -> Option<(K, V)> {
2193        self.inner.next(&mut self.pred, self.alloc.clone())
2194    }
2195
2196    fn size_hint(&self) -> (usize, Option<usize>) {
2197        self.inner.size_hint()
2198    }
2199}
2200
2201impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2202    /// Allow Debug implementations to predict the next element.
2203    pub(super) fn peek(&self) -> Option<(&K, &V)> {
2204        let edge = self.cur_leaf_edge.as_ref()?;
2205        edge.reborrow().next_kv().ok().map(Handle::into_kv)
2206    }
2207
2208    /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2209    pub(super) fn next<F, A: AllocatorClone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2210    where
2211        K: PartialOrd,
2212        R: RangeBounds<K>,
2213        F: FnMut(&K, &mut V) -> bool,
2214    {
2215        while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2216            let (k, v) = kv.kv_mut();
2217
2218            // On creation, we navigated directly to the left bound, so we need only check the
2219            // right bound here to decide whether to stop.
2220            match self.range.end_bound() {
2221                Bound::Included(end) if (*k).le(end) => (),
2222                Bound::Excluded(end) if (*k).lt(end) => (),
2223                Bound::Unbounded => (),
2224                _ => return None,
2225            }
2226
2227            if pred(k, v) {
2228                *self.length -= 1;
2229                let (kv, pos) = kv.remove_kv_tracking(
2230                    || {
2231                        // SAFETY: we will touch the root in a way that will not
2232                        // invalidate the position returned.
2233                        let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2234                        root.pop_internal_level(alloc.clone());
2235                        self.dormant_root = Some(DormantMutRef::new(root).1);
2236                    },
2237                    alloc.clone(),
2238                );
2239                self.cur_leaf_edge = Some(pos);
2240                return Some(kv);
2241            }
2242            self.cur_leaf_edge = Some(kv.next_leaf_edge());
2243        }
2244        None
2245    }
2246
2247    /// Implementation of a typical `ExtractIf::size_hint` method.
2248    pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2249        // In most of the btree iterators, `self.length` is the number of elements
2250        // yet to be visited. Here, it includes elements that were visited and that
2251        // the predicate decided not to drain. Making this upper bound more tight
2252        // during iteration would require an extra field.
2253        (0, Some(*self.length))
2254    }
2255}
2256
2257#[stable(feature = "btree_extract_if", since = "1.91.0")]
2258impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2259where
2260    K: PartialOrd,
2261    R: RangeBounds<K>,
2262    F: FnMut(&K, &mut V) -> bool,
2263{
2264}
2265
2266#[stable(feature = "btree_range", since = "1.17.0")]
2267impl<'a, K, V> Iterator for Range<'a, K, V> {
2268    type Item = (&'a K, &'a V);
2269
2270    fn next(&mut self) -> Option<(&'a K, &'a V)> {
2271        self.inner.next_checked()
2272    }
2273
2274    fn last(mut self) -> Option<(&'a K, &'a V)> {
2275        self.next_back()
2276    }
2277
2278    fn min(mut self) -> Option<(&'a K, &'a V)>
2279    where
2280        (&'a K, &'a V): Ord,
2281    {
2282        self.next()
2283    }
2284
2285    fn max(mut self) -> Option<(&'a K, &'a V)>
2286    where
2287        (&'a K, &'a V): Ord,
2288    {
2289        self.next_back()
2290    }
2291}
2292
2293#[stable(feature = "default_iters", since = "1.70.0")]
2294impl<K, V> Default for Range<'_, K, V> {
2295    /// Creates an empty `btree_map::Range`.
2296    ///
2297    /// ```
2298    /// # use std::collections::btree_map;
2299    /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2300    /// assert_eq!(iter.count(), 0);
2301    /// ```
2302    fn default() -> Self {
2303        Range { inner: Default::default() }
2304    }
2305}
2306
2307#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2308impl<K, V> Default for RangeMut<'_, K, V> {
2309    /// Creates an empty `btree_map::RangeMut`.
2310    ///
2311    /// ```
2312    /// # use std::collections::btree_map;
2313    /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2314    /// assert_eq!(iter.count(), 0);
2315    /// ```
2316    fn default() -> Self {
2317        RangeMut { inner: Default::default(), _marker: PhantomData }
2318    }
2319}
2320
2321#[stable(feature = "map_values_mut", since = "1.10.0")]
2322impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2323    type Item = &'a mut V;
2324
2325    fn next(&mut self) -> Option<&'a mut V> {
2326        self.inner.next().map(|(_, v)| v)
2327    }
2328
2329    fn size_hint(&self) -> (usize, Option<usize>) {
2330        self.inner.size_hint()
2331    }
2332
2333    fn last(mut self) -> Option<&'a mut V> {
2334        self.next_back()
2335    }
2336}
2337
2338#[stable(feature = "map_values_mut", since = "1.10.0")]
2339impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2340    fn next_back(&mut self) -> Option<&'a mut V> {
2341        self.inner.next_back().map(|(_, v)| v)
2342    }
2343}
2344
2345#[stable(feature = "map_values_mut", since = "1.10.0")]
2346impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2347    fn len(&self) -> usize {
2348        self.inner.len()
2349    }
2350}
2351
2352#[unstable(feature = "trusted_len", issue = "37572")]
2353unsafe impl<K, V> TrustedLen for ValuesMut<'_, K, V> {}
2354
2355#[stable(feature = "fused", since = "1.26.0")]
2356impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2357
2358#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2359impl<K, V> Default for ValuesMut<'_, K, V> {
2360    /// Creates an empty `btree_map::ValuesMut`.
2361    ///
2362    /// ```
2363    /// # use std::collections::btree_map;
2364    /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2365    /// assert_eq!(iter.count(), 0);
2366    /// ```
2367    fn default() -> Self {
2368        ValuesMut { inner: Default::default() }
2369    }
2370}
2371
2372#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2373impl<K, V, A: AllocatorClone> Iterator for IntoKeys<K, V, A> {
2374    type Item = K;
2375
2376    fn next(&mut self) -> Option<K> {
2377        self.inner.next().map(|(k, _)| k)
2378    }
2379
2380    fn size_hint(&self) -> (usize, Option<usize>) {
2381        self.inner.size_hint()
2382    }
2383
2384    fn last(mut self) -> Option<K> {
2385        self.next_back()
2386    }
2387
2388    fn min(mut self) -> Option<K>
2389    where
2390        K: Ord,
2391    {
2392        self.next()
2393    }
2394
2395    fn max(mut self) -> Option<K>
2396    where
2397        K: Ord,
2398    {
2399        self.next_back()
2400    }
2401}
2402
2403#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2404impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoKeys<K, V, A> {
2405    fn next_back(&mut self) -> Option<K> {
2406        self.inner.next_back().map(|(k, _)| k)
2407    }
2408}
2409
2410#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2411impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoKeys<K, V, A> {
2412    fn len(&self) -> usize {
2413        self.inner.len()
2414    }
2415}
2416
2417#[unstable(feature = "trusted_len", issue = "37572")]
2418unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoKeys<K, V, A> {}
2419
2420#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2421impl<K, V, A: AllocatorClone> FusedIterator for IntoKeys<K, V, A> {}
2422
2423#[stable(feature = "default_iters", since = "1.70.0")]
2424impl<K, V, A> Default for IntoKeys<K, V, A>
2425where
2426    A: AllocatorClone + Default,
2427{
2428    /// Creates an empty `btree_map::IntoKeys`.
2429    ///
2430    /// ```
2431    /// # use std::collections::btree_map;
2432    /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2433    /// assert_eq!(iter.len(), 0);
2434    /// ```
2435    fn default() -> Self {
2436        IntoKeys { inner: Default::default() }
2437    }
2438}
2439
2440#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2441impl<K, V, A: AllocatorClone> Iterator for IntoValues<K, V, A> {
2442    type Item = V;
2443
2444    fn next(&mut self) -> Option<V> {
2445        self.inner.next().map(|(_, v)| v)
2446    }
2447
2448    fn size_hint(&self) -> (usize, Option<usize>) {
2449        self.inner.size_hint()
2450    }
2451
2452    fn last(mut self) -> Option<V> {
2453        self.next_back()
2454    }
2455}
2456
2457#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2458impl<K, V, A: AllocatorClone> DoubleEndedIterator for IntoValues<K, V, A> {
2459    fn next_back(&mut self) -> Option<V> {
2460        self.inner.next_back().map(|(_, v)| v)
2461    }
2462}
2463
2464#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2465impl<K, V, A: AllocatorClone> ExactSizeIterator for IntoValues<K, V, A> {
2466    fn len(&self) -> usize {
2467        self.inner.len()
2468    }
2469}
2470
2471#[unstable(feature = "trusted_len", issue = "37572")]
2472unsafe impl<K, V, A: AllocatorClone> TrustedLen for IntoValues<K, V, A> {}
2473
2474#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2475impl<K, V, A: AllocatorClone> FusedIterator for IntoValues<K, V, A> {}
2476
2477#[stable(feature = "default_iters", since = "1.70.0")]
2478impl<K, V, A> Default for IntoValues<K, V, A>
2479where
2480    A: AllocatorClone + Default,
2481{
2482    /// Creates an empty `btree_map::IntoValues`.
2483    ///
2484    /// ```
2485    /// # use std::collections::btree_map;
2486    /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2487    /// assert_eq!(iter.len(), 0);
2488    /// ```
2489    fn default() -> Self {
2490        IntoValues { inner: Default::default() }
2491    }
2492}
2493
2494#[stable(feature = "btree_range", since = "1.17.0")]
2495impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2496    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2497        self.inner.next_back_checked()
2498    }
2499}
2500
2501#[stable(feature = "fused", since = "1.26.0")]
2502impl<K, V> FusedIterator for Range<'_, K, V> {}
2503
2504#[stable(feature = "btree_range", since = "1.17.0")]
2505impl<K, V> Clone for Range<'_, K, V> {
2506    fn clone(&self) -> Self {
2507        Range { inner: self.inner.clone() }
2508    }
2509}
2510
2511#[stable(feature = "btree_range", since = "1.17.0")]
2512impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2513    type Item = (&'a K, &'a mut V);
2514
2515    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2516        self.inner.next_checked()
2517    }
2518
2519    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2520        self.next_back()
2521    }
2522
2523    fn min(mut self) -> Option<(&'a K, &'a mut V)>
2524    where
2525        (&'a K, &'a mut V): Ord,
2526    {
2527        self.next()
2528    }
2529
2530    fn max(mut self) -> Option<(&'a K, &'a mut V)>
2531    where
2532        (&'a K, &'a mut V): Ord,
2533    {
2534        self.next_back()
2535    }
2536}
2537
2538#[stable(feature = "btree_range", since = "1.17.0")]
2539impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2540    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2541        self.inner.next_back_checked()
2542    }
2543}
2544
2545#[stable(feature = "fused", since = "1.26.0")]
2546impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2547
2548#[stable(feature = "rust1", since = "1.0.0")]
2549impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2550    /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2551    ///
2552    /// If the iterator produces any pairs with equal keys,
2553    /// all but one of the corresponding values will be dropped.
2554    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> BTreeMap<K, V> {
2555        let mut inputs: Vec<_> = iter.into_iter().collect();
2556
2557        if inputs.is_empty() {
2558            return BTreeMap::new();
2559        }
2560
2561        // use stable sort to preserve the insertion order.
2562        inputs.sort_by(|a, b| a.0.cmp(&b.0));
2563        BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2564    }
2565}
2566
2567#[stable(feature = "rust1", since = "1.0.0")]
2568impl<K: Ord, V, A: AllocatorClone> Extend<(K, V)> for BTreeMap<K, V, A> {
2569    #[inline]
2570    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
2571        iter.into_iter().for_each(move |(k, v)| {
2572            self.insert(k, v);
2573        });
2574    }
2575
2576    #[inline]
2577    fn extend_one(&mut self, (k, v): (K, V)) {
2578        self.insert(k, v);
2579    }
2580}
2581
2582#[stable(feature = "extend_ref", since = "1.2.0")]
2583impl<'a, K: Ord + Copy, V: Copy, A: AllocatorClone> Extend<(&'a K, &'a V)> for BTreeMap<K, V, A> {
2584    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2585        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2586    }
2587
2588    #[inline]
2589    fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2590        self.insert(k, v);
2591    }
2592}
2593
2594#[stable(feature = "rust1", since = "1.0.0")]
2595impl<K: Hash, V: Hash, A: AllocatorClone> Hash for BTreeMap<K, V, A> {
2596    fn hash<H: Hasher>(&self, state: &mut H) {
2597        state.write_length_prefix(self.len());
2598        for elt in self {
2599            elt.hash(state);
2600        }
2601    }
2602}
2603
2604#[stable(feature = "rust1", since = "1.0.0")]
2605#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2606const impl<K, V> Default for BTreeMap<K, V> {
2607    /// Creates an empty `BTreeMap`.
2608    fn default() -> BTreeMap<K, V> {
2609        BTreeMap::new()
2610    }
2611}
2612
2613#[stable(feature = "rust1", since = "1.0.0")]
2614impl<K: PartialEq, V: PartialEq, A: AllocatorClone> PartialEq for BTreeMap<K, V, A> {
2615    fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2616        self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2617    }
2618}
2619
2620#[stable(feature = "rust1", since = "1.0.0")]
2621impl<K: Eq, V: Eq, A: AllocatorClone> Eq for BTreeMap<K, V, A> {}
2622
2623#[stable(feature = "rust1", since = "1.0.0")]
2624impl<K: PartialOrd, V: PartialOrd, A: AllocatorClone> PartialOrd for BTreeMap<K, V, A> {
2625    #[inline]
2626    fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2627        self.iter().partial_cmp(other.iter())
2628    }
2629}
2630
2631#[stable(feature = "rust1", since = "1.0.0")]
2632impl<K: Ord, V: Ord, A: AllocatorClone> Ord for BTreeMap<K, V, A> {
2633    #[inline]
2634    fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2635        self.iter().cmp(other.iter())
2636    }
2637}
2638
2639#[stable(feature = "rust1", since = "1.0.0")]
2640impl<K: Debug, V: Debug, A: AllocatorClone> Debug for BTreeMap<K, V, A> {
2641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2642        f.debug_map().entries(self.iter()).finish()
2643    }
2644}
2645
2646#[stable(feature = "rust1", since = "1.0.0")]
2647impl<K, Q: ?Sized, V, A: AllocatorClone> Index<&Q> for BTreeMap<K, V, A>
2648where
2649    K: Borrow<Q> + Ord,
2650    Q: Ord,
2651{
2652    type Output = V;
2653
2654    /// Returns a reference to the value corresponding to the supplied key.
2655    ///
2656    /// # Panics
2657    ///
2658    /// Panics if the key is not present in the `BTreeMap`.
2659    #[inline]
2660    fn index(&self, key: &Q) -> &V {
2661        self.get(key).expect("no entry found for key")
2662    }
2663}
2664
2665#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2666impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2667    /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2668    ///
2669    /// If any entries in the array have equal keys,
2670    /// all but one of the corresponding values will be dropped.
2671    ///
2672    /// ```
2673    /// use std::collections::BTreeMap;
2674    ///
2675    /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2676    /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2677    /// assert_eq!(map1, map2);
2678    /// ```
2679    fn from(mut arr: [(K, V); N]) -> Self {
2680        if N == 0 {
2681            return BTreeMap::new();
2682        }
2683
2684        // use stable sort to preserve the insertion order.
2685        arr.sort_by(|a, b| a.0.cmp(&b.0));
2686        BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2687    }
2688}
2689
2690impl<K, V, A: AllocatorClone> BTreeMap<K, V, A> {
2691    /// Gets an iterator over the entries of the map, sorted by key.
2692    ///
2693    /// # Examples
2694    ///
2695    /// ```
2696    /// use std::collections::BTreeMap;
2697    ///
2698    /// let mut map = BTreeMap::new();
2699    /// map.insert(3, "c");
2700    /// map.insert(2, "b");
2701    /// map.insert(1, "a");
2702    ///
2703    /// for (key, value) in map.iter() {
2704    ///     println!("{key}: {value}");
2705    /// }
2706    ///
2707    /// let (first_key, first_value) = map.iter().next().unwrap();
2708    /// assert_eq!((*first_key, *first_value), (1, "a"));
2709    /// ```
2710    #[stable(feature = "rust1", since = "1.0.0")]
2711    pub fn iter(&self) -> Iter<'_, K, V> {
2712        if let Some(root) = &self.root {
2713            let full_range = root.reborrow().full_range();
2714
2715            Iter { range: full_range, length: self.length }
2716        } else {
2717            Iter { range: LazyLeafRange::none(), length: 0 }
2718        }
2719    }
2720
2721    /// Gets a mutable iterator over the entries of the map, sorted by key.
2722    ///
2723    /// # Examples
2724    ///
2725    /// ```
2726    /// use std::collections::BTreeMap;
2727    ///
2728    /// let mut map = BTreeMap::from([
2729    ///    ("a", 1),
2730    ///    ("b", 2),
2731    ///    ("c", 3),
2732    /// ]);
2733    ///
2734    /// // add 10 to the value if the key isn't "a"
2735    /// for (key, value) in map.iter_mut() {
2736    ///     if key != &"a" {
2737    ///         *value += 10;
2738    ///     }
2739    /// }
2740    /// ```
2741    #[stable(feature = "rust1", since = "1.0.0")]
2742    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2743        if let Some(root) = &mut self.root {
2744            let full_range = root.borrow_valmut().full_range();
2745
2746            IterMut { range: full_range, length: self.length, _marker: PhantomData }
2747        } else {
2748            IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2749        }
2750    }
2751
2752    /// Gets an iterator over the keys of the map, in sorted order.
2753    ///
2754    /// # Examples
2755    ///
2756    /// ```
2757    /// use std::collections::BTreeMap;
2758    ///
2759    /// let mut a = BTreeMap::new();
2760    /// a.insert(2, "b");
2761    /// a.insert(1, "a");
2762    ///
2763    /// let keys: Vec<_> = a.keys().cloned().collect();
2764    /// assert_eq!(keys, [1, 2]);
2765    /// ```
2766    #[stable(feature = "rust1", since = "1.0.0")]
2767    pub fn keys(&self) -> Keys<'_, K, V> {
2768        Keys { inner: self.iter() }
2769    }
2770
2771    /// Gets an iterator over the values of the map, in order by key.
2772    ///
2773    /// # Examples
2774    ///
2775    /// ```
2776    /// use std::collections::BTreeMap;
2777    ///
2778    /// let mut a = BTreeMap::new();
2779    /// a.insert(1, "hello");
2780    /// a.insert(2, "goodbye");
2781    ///
2782    /// let values: Vec<&str> = a.values().cloned().collect();
2783    /// assert_eq!(values, ["hello", "goodbye"]);
2784    /// ```
2785    #[stable(feature = "rust1", since = "1.0.0")]
2786    pub fn values(&self) -> Values<'_, K, V> {
2787        Values { inner: self.iter() }
2788    }
2789
2790    /// Gets a mutable iterator over the values of the map, in order by key.
2791    ///
2792    /// # Examples
2793    ///
2794    /// ```
2795    /// use std::collections::BTreeMap;
2796    ///
2797    /// let mut a = BTreeMap::new();
2798    /// a.insert(1, String::from("hello"));
2799    /// a.insert(2, String::from("goodbye"));
2800    ///
2801    /// for value in a.values_mut() {
2802    ///     value.push_str("!");
2803    /// }
2804    ///
2805    /// let values: Vec<String> = a.values().cloned().collect();
2806    /// assert_eq!(values, [String::from("hello!"),
2807    ///                     String::from("goodbye!")]);
2808    /// ```
2809    #[stable(feature = "map_values_mut", since = "1.10.0")]
2810    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2811        ValuesMut { inner: self.iter_mut() }
2812    }
2813
2814    /// Returns the number of elements in the map.
2815    ///
2816    /// # Examples
2817    ///
2818    /// ```
2819    /// use std::collections::BTreeMap;
2820    ///
2821    /// let mut a = BTreeMap::new();
2822    /// assert_eq!(a.len(), 0);
2823    /// a.insert(1, "a");
2824    /// assert_eq!(a.len(), 1);
2825    /// ```
2826    #[must_use]
2827    #[stable(feature = "rust1", since = "1.0.0")]
2828    #[rustc_const_unstable(
2829        feature = "const_btree_len",
2830        issue = "71835",
2831        implied_by = "const_btree_new"
2832    )]
2833    #[rustc_confusables("length", "size")]
2834    pub const fn len(&self) -> usize {
2835        self.length
2836    }
2837
2838    /// Returns `true` if the map contains no elements.
2839    ///
2840    /// # Examples
2841    ///
2842    /// ```
2843    /// use std::collections::BTreeMap;
2844    ///
2845    /// let mut a = BTreeMap::new();
2846    /// assert!(a.is_empty());
2847    /// a.insert(1, "a");
2848    /// assert!(!a.is_empty());
2849    /// ```
2850    #[must_use]
2851    #[stable(feature = "rust1", since = "1.0.0")]
2852    #[rustc_const_unstable(
2853        feature = "const_btree_len",
2854        issue = "71835",
2855        implied_by = "const_btree_new"
2856    )]
2857    pub const fn is_empty(&self) -> bool {
2858        self.len() == 0
2859    }
2860
2861    /// Returns a [`Cursor`] pointing at the gap before the smallest key
2862    /// greater than the given bound.
2863    ///
2864    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2865    /// gap before the smallest key greater than or equal to `x`.
2866    ///
2867    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2868    /// gap before the smallest key greater than `x`.
2869    ///
2870    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2871    /// gap before the smallest key in the map.
2872    ///
2873    /// # Examples
2874    ///
2875    /// ```
2876    /// #![feature(btree_cursors)]
2877    ///
2878    /// use std::collections::BTreeMap;
2879    /// use std::ops::Bound;
2880    ///
2881    /// let map = BTreeMap::from([
2882    ///     (1, "a"),
2883    ///     (2, "b"),
2884    ///     (3, "c"),
2885    ///     (4, "d"),
2886    /// ]);
2887    ///
2888    /// let cursor = map.lower_bound(Bound::Included(&2));
2889    /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2890    /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2891    ///
2892    /// let cursor = map.lower_bound(Bound::Excluded(&2));
2893    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2894    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2895    ///
2896    /// let cursor = map.lower_bound(Bound::Unbounded);
2897    /// assert_eq!(cursor.peek_prev(), None);
2898    /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2899    /// ```
2900    #[unstable(feature = "btree_cursors", issue = "107540")]
2901    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2902    where
2903        K: Borrow<Q> + Ord,
2904        Q: Ord,
2905    {
2906        let root_node = match self.root.as_ref() {
2907            None => return Cursor { current: None, root: None },
2908            Some(root) => root.reborrow(),
2909        };
2910        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2911        Cursor { current: Some(edge), root: self.root.as_ref() }
2912    }
2913
2914    /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2915    /// greater than the given bound.
2916    ///
2917    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2918    /// gap before the smallest key greater than or equal to `x`.
2919    ///
2920    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2921    /// gap before the smallest key greater than `x`.
2922    ///
2923    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2924    /// gap before the smallest key in the map.
2925    ///
2926    /// # Examples
2927    ///
2928    /// ```
2929    /// #![feature(btree_cursors)]
2930    ///
2931    /// use std::collections::BTreeMap;
2932    /// use std::ops::Bound;
2933    ///
2934    /// let mut map = BTreeMap::from([
2935    ///     (1, "a"),
2936    ///     (2, "b"),
2937    ///     (3, "c"),
2938    ///     (4, "d"),
2939    /// ]);
2940    ///
2941    /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2942    /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2943    /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2944    ///
2945    /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2946    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2947    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2948    ///
2949    /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2950    /// assert_eq!(cursor.peek_prev(), None);
2951    /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2952    /// ```
2953    #[unstable(feature = "btree_cursors", issue = "107540")]
2954    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2955    where
2956        K: Borrow<Q> + Ord,
2957        Q: Ord,
2958    {
2959        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2960        let root_node = match root.as_mut() {
2961            None => {
2962                return CursorMut {
2963                    inner: CursorMutKey {
2964                        current: None,
2965                        root: dormant_root,
2966                        length: &mut self.length,
2967                        alloc: &mut *self.alloc,
2968                    },
2969                };
2970            }
2971            Some(root) => root.borrow_mut(),
2972        };
2973        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2974        CursorMut {
2975            inner: CursorMutKey {
2976                current: Some(edge),
2977                root: dormant_root,
2978                length: &mut self.length,
2979                alloc: &mut *self.alloc,
2980            },
2981        }
2982    }
2983
2984    /// Returns a [`Cursor`] pointing at the gap after the greatest key
2985    /// smaller than the given bound.
2986    ///
2987    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2988    /// gap after the greatest key smaller than or equal to `x`.
2989    ///
2990    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2991    /// gap after the greatest key smaller than `x`.
2992    ///
2993    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2994    /// gap after the greatest key in the map.
2995    ///
2996    /// # Examples
2997    ///
2998    /// ```
2999    /// #![feature(btree_cursors)]
3000    ///
3001    /// use std::collections::BTreeMap;
3002    /// use std::ops::Bound;
3003    ///
3004    /// let map = BTreeMap::from([
3005    ///     (1, "a"),
3006    ///     (2, "b"),
3007    ///     (3, "c"),
3008    ///     (4, "d"),
3009    /// ]);
3010    ///
3011    /// let cursor = map.upper_bound(Bound::Included(&3));
3012    /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
3013    /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
3014    ///
3015    /// let cursor = map.upper_bound(Bound::Excluded(&3));
3016    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
3017    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
3018    ///
3019    /// let cursor = map.upper_bound(Bound::Unbounded);
3020    /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
3021    /// assert_eq!(cursor.peek_next(), None);
3022    /// ```
3023    #[unstable(feature = "btree_cursors", issue = "107540")]
3024    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
3025    where
3026        K: Borrow<Q> + Ord,
3027        Q: Ord,
3028    {
3029        let root_node = match self.root.as_ref() {
3030            None => return Cursor { current: None, root: None },
3031            Some(root) => root.reborrow(),
3032        };
3033        let edge = root_node.upper_bound(SearchBound::from_range(bound));
3034        Cursor { current: Some(edge), root: self.root.as_ref() }
3035    }
3036
3037    /// Returns a [`CursorMut`] pointing at the gap after the greatest key
3038    /// smaller than the given bound.
3039    ///
3040    /// Passing `Bound::Included(x)` will return a cursor pointing to the
3041    /// gap after the greatest key smaller than or equal to `x`.
3042    ///
3043    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
3044    /// gap after the greatest key smaller than `x`.
3045    ///
3046    /// Passing `Bound::Unbounded` will return a cursor pointing to the
3047    /// gap after the greatest key in the map.
3048    ///
3049    /// # Examples
3050    ///
3051    /// ```
3052    /// #![feature(btree_cursors)]
3053    ///
3054    /// use std::collections::BTreeMap;
3055    /// use std::ops::Bound;
3056    ///
3057    /// let mut map = BTreeMap::from([
3058    ///     (1, "a"),
3059    ///     (2, "b"),
3060    ///     (3, "c"),
3061    ///     (4, "d"),
3062    /// ]);
3063    ///
3064    /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
3065    /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
3066    /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
3067    ///
3068    /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
3069    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
3070    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
3071    ///
3072    /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
3073    /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
3074    /// assert_eq!(cursor.peek_next(), None);
3075    /// ```
3076    #[unstable(feature = "btree_cursors", issue = "107540")]
3077    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
3078    where
3079        K: Borrow<Q> + Ord,
3080        Q: Ord,
3081    {
3082        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
3083        let root_node = match root.as_mut() {
3084            None => {
3085                return CursorMut {
3086                    inner: CursorMutKey {
3087                        current: None,
3088                        root: dormant_root,
3089                        length: &mut self.length,
3090                        alloc: &mut *self.alloc,
3091                    },
3092                };
3093            }
3094            Some(root) => root.borrow_mut(),
3095        };
3096        let edge = root_node.upper_bound(SearchBound::from_range(bound));
3097        CursorMut {
3098            inner: CursorMutKey {
3099                current: Some(edge),
3100                root: dormant_root,
3101                length: &mut self.length,
3102                alloc: &mut *self.alloc,
3103            },
3104        }
3105    }
3106}
3107
3108/// A cursor over a `BTreeMap`.
3109///
3110/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
3111///
3112/// Cursors always point to a gap between two elements in the map, and can
3113/// operate on the two immediately adjacent elements.
3114///
3115/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
3116#[unstable(feature = "btree_cursors", issue = "107540")]
3117pub struct Cursor<'a, K: 'a, V: 'a> {
3118    // If current is None then it means the tree has not been allocated yet.
3119    current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3120    root: Option<&'a node::Root<K, V>>,
3121}
3122
3123#[unstable(feature = "btree_cursors", issue = "107540")]
3124impl<K, V> Clone for Cursor<'_, K, V> {
3125    fn clone(&self) -> Self {
3126        let Cursor { current, root } = *self;
3127        Cursor { current, root }
3128    }
3129}
3130
3131#[unstable(feature = "btree_cursors", issue = "107540")]
3132impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
3133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3134        f.write_str("Cursor")
3135    }
3136}
3137
3138/// A cursor over a `BTreeMap` with editing operations.
3139///
3140/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3141/// safely mutate the map during iteration. This is because the lifetime of its yielded
3142/// references is tied to its own lifetime, instead of just the underlying map. This means
3143/// cursors cannot yield multiple elements at once.
3144///
3145/// Cursors always point to a gap between two elements in the map, and can
3146/// operate on the two immediately adjacent elements.
3147///
3148/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
3149/// methods.
3150#[unstable(feature = "btree_cursors", issue = "107540")]
3151pub struct CursorMut<
3152    'a,
3153    K: 'a,
3154    V: 'a,
3155    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3156> {
3157    inner: CursorMutKey<'a, K, V, A>,
3158}
3159
3160#[unstable(feature = "btree_cursors", issue = "107540")]
3161impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
3162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3163        f.write_str("CursorMut")
3164    }
3165}
3166
3167/// A cursor over a `BTreeMap` with editing operations, and which allows
3168/// mutating the key of elements.
3169///
3170/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3171/// safely mutate the map during iteration. This is because the lifetime of its yielded
3172/// references is tied to its own lifetime, instead of just the underlying map. This means
3173/// cursors cannot yield multiple elements at once.
3174///
3175/// Cursors always point to a gap between two elements in the map, and can
3176/// operate on the two immediately adjacent elements.
3177///
3178/// A `CursorMutKey` is created from a [`CursorMut`] with the
3179/// [`CursorMut::with_mutable_key`] method.
3180///
3181/// # Safety
3182///
3183/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3184/// invariants are maintained. Specifically:
3185///
3186/// * The key of the newly inserted element must be unique in the tree.
3187/// * All keys in the tree must remain in sorted order.
3188#[unstable(feature = "btree_cursors", issue = "107540")]
3189pub struct CursorMutKey<
3190    'a,
3191    K: 'a,
3192    V: 'a,
3193    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3194> {
3195    // If current is None then it means the tree has not been allocated yet.
3196    current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3197    root: DormantMutRef<'a, Option<node::Root<K, V>>>,
3198    length: &'a mut usize,
3199    alloc: &'a mut A,
3200}
3201
3202#[unstable(feature = "btree_cursors", issue = "107540")]
3203impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
3204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3205        f.write_str("CursorMutKey")
3206    }
3207}
3208
3209impl<'a, K, V> Cursor<'a, K, V> {
3210    /// Advances the cursor to the next gap, returning the key and value of the
3211    /// element that it moved over.
3212    ///
3213    /// If the cursor is already at the end of the map then `None` is returned
3214    /// and the cursor is not moved.
3215    #[unstable(feature = "btree_cursors", issue = "107540")]
3216    pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3217        let current = self.current.take()?;
3218        match current.next_kv() {
3219            Ok(kv) => {
3220                let result = kv.into_kv();
3221                self.current = Some(kv.next_leaf_edge());
3222                Some(result)
3223            }
3224            Err(root) => {
3225                self.current = Some(root.last_leaf_edge());
3226                None
3227            }
3228        }
3229    }
3230
3231    /// Advances the cursor to the previous gap, returning the key and value of
3232    /// the element that it moved over.
3233    ///
3234    /// If the cursor is already at the start of the map then `None` is returned
3235    /// and the cursor is not moved.
3236    #[unstable(feature = "btree_cursors", issue = "107540")]
3237    pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3238        let current = self.current.take()?;
3239        match current.next_back_kv() {
3240            Ok(kv) => {
3241                let result = kv.into_kv();
3242                self.current = Some(kv.next_back_leaf_edge());
3243                Some(result)
3244            }
3245            Err(root) => {
3246                self.current = Some(root.first_leaf_edge());
3247                None
3248            }
3249        }
3250    }
3251
3252    /// Returns a reference to the key and value of the next element without
3253    /// moving the cursor.
3254    ///
3255    /// If the cursor is at the end of the map then `None` is returned.
3256    #[unstable(feature = "btree_cursors", issue = "107540")]
3257    pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3258        self.clone().next()
3259    }
3260
3261    /// Returns a reference to the key and value of the previous element
3262    /// without moving the cursor.
3263    ///
3264    /// If the cursor is at the start of the map then `None` is returned.
3265    #[unstable(feature = "btree_cursors", issue = "107540")]
3266    pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3267        self.clone().prev()
3268    }
3269}
3270
3271impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3272    /// Advances the cursor to the next gap, returning the key and value of the
3273    /// element that it moved over.
3274    ///
3275    /// If the cursor is already at the end of the map then `None` is returned
3276    /// and the cursor is not moved.
3277    #[unstable(feature = "btree_cursors", issue = "107540")]
3278    pub fn next(&mut self) -> Option<(&K, &mut V)> {
3279        let (k, v) = self.inner.next()?;
3280        Some((&*k, v))
3281    }
3282
3283    /// Advances the cursor to the previous gap, returning the key and value of
3284    /// the element that it moved over.
3285    ///
3286    /// If the cursor is already at the start of the map then `None` is returned
3287    /// and the cursor is not moved.
3288    #[unstable(feature = "btree_cursors", issue = "107540")]
3289    pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3290        let (k, v) = self.inner.prev()?;
3291        Some((&*k, v))
3292    }
3293
3294    /// Returns a reference to the key and value of the next element without
3295    /// moving the cursor.
3296    ///
3297    /// If the cursor is at the end of the map then `None` is returned.
3298    #[unstable(feature = "btree_cursors", issue = "107540")]
3299    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3300        let (k, v) = self.inner.peek_next()?;
3301        Some((&*k, v))
3302    }
3303
3304    /// Returns a reference to the key and value of the previous element
3305    /// without moving the cursor.
3306    ///
3307    /// If the cursor is at the start of the map then `None` is returned.
3308    #[unstable(feature = "btree_cursors", issue = "107540")]
3309    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3310        let (k, v) = self.inner.peek_prev()?;
3311        Some((&*k, v))
3312    }
3313
3314    /// Returns a read-only cursor pointing to the same location as the
3315    /// `CursorMut`.
3316    ///
3317    /// The lifetime of the returned `Cursor` is bound to that of the
3318    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3319    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3320    #[unstable(feature = "btree_cursors", issue = "107540")]
3321    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3322        self.inner.as_cursor()
3323    }
3324
3325    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3326    /// the key of elements in the tree.
3327    ///
3328    /// # Safety
3329    ///
3330    /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3331    /// invariants are maintained. Specifically:
3332    ///
3333    /// * The key of the newly inserted element must be unique in the tree.
3334    /// * All keys in the tree must remain in sorted order.
3335    #[unstable(feature = "btree_cursors", issue = "107540")]
3336    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3337        self.inner
3338    }
3339}
3340
3341impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3342    /// Advances the cursor to the next gap, returning the key and value of the
3343    /// element that it moved over.
3344    ///
3345    /// If the cursor is already at the end of the map then `None` is returned
3346    /// and the cursor is not moved.
3347    #[unstable(feature = "btree_cursors", issue = "107540")]
3348    pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3349        let current = self.current.take()?;
3350        match current.next_kv() {
3351            Ok(mut kv) => {
3352                // SAFETY: The key/value pointers remain valid even after the
3353                // cursor is moved forward. The lifetimes then prevent any
3354                // further access to the cursor.
3355                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3356                let (k, v) = (k as *mut _, v as *mut _);
3357                self.current = Some(kv.next_leaf_edge());
3358                // ignore-tidy-undocumented-unsafe
3359                Some(unsafe { (&mut *k, &mut *v) })
3360            }
3361            Err(root) => {
3362                self.current = Some(root.last_leaf_edge());
3363                None
3364            }
3365        }
3366    }
3367
3368    /// Advances the cursor to the previous gap, returning the key and value of
3369    /// the element that it moved over.
3370    ///
3371    /// If the cursor is already at the start of the map then `None` is returned
3372    /// and the cursor is not moved.
3373    #[unstable(feature = "btree_cursors", issue = "107540")]
3374    pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3375        let current = self.current.take()?;
3376        match current.next_back_kv() {
3377            Ok(mut kv) => {
3378                // SAFETY: The key/value pointers remain valid even after the
3379                // cursor is moved forward. The lifetimes then prevent any
3380                // further access to the cursor.
3381                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3382                let (k, v) = (k as *mut _, v as *mut _);
3383                self.current = Some(kv.next_back_leaf_edge());
3384                // ignore-tidy-undocumented-unsafe
3385                Some(unsafe { (&mut *k, &mut *v) })
3386            }
3387            Err(root) => {
3388                self.current = Some(root.first_leaf_edge());
3389                None
3390            }
3391        }
3392    }
3393
3394    /// Returns a reference to the key and value of the next element without
3395    /// moving the cursor.
3396    ///
3397    /// If the cursor is at the end of the map then `None` is returned.
3398    #[unstable(feature = "btree_cursors", issue = "107540")]
3399    pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3400        let current = self.current.as_mut()?;
3401        // SAFETY: We're not using this to mutate the tree.
3402        let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3403        Some(kv)
3404    }
3405
3406    /// Returns a reference to the key and value of the previous element
3407    /// without moving the cursor.
3408    ///
3409    /// If the cursor is at the start of the map then `None` is returned.
3410    #[unstable(feature = "btree_cursors", issue = "107540")]
3411    pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3412        let current = self.current.as_mut()?;
3413        // SAFETY: We're not using this to mutate the tree.
3414        let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3415        Some(kv)
3416    }
3417
3418    /// Returns a read-only cursor pointing to the same location as the
3419    /// `CursorMutKey`.
3420    ///
3421    /// The lifetime of the returned `Cursor` is bound to that of the
3422    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3423    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3424    #[unstable(feature = "btree_cursors", issue = "107540")]
3425    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3426        Cursor {
3427            // SAFETY: The tree is immutable while the cursor exists.
3428            root: unsafe { self.root.reborrow_shared().as_ref() },
3429            current: self.current.as_ref().map(|current| current.reborrow()),
3430        }
3431    }
3432}
3433
3434// Now the tree editing operations
3435impl<'a, K: Ord, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> {
3436    /// Inserts a new key-value pair into the map in the gap that the
3437    /// cursor is currently pointing to.
3438    ///
3439    /// After the insertion the cursor will be pointing at the gap before the
3440    /// newly inserted element.
3441    ///
3442    /// # Safety
3443    ///
3444    /// You must ensure that the `BTreeMap` invariants are maintained.
3445    /// Specifically:
3446    ///
3447    /// * The key of the newly inserted element must be unique in the tree.
3448    /// * All keys in the tree must remain in sorted order.
3449    #[unstable(feature = "btree_cursors", issue = "107540")]
3450    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3451        let edge = match self.current.take() {
3452            None => {
3453                // Tree is empty, allocate a new root.
3454                // SAFETY: We have no other reference to the tree.
3455                let root = unsafe { self.root.reborrow() };
3456                debug_assert!(root.is_none());
3457                let mut node = NodeRef::new_leaf(self.alloc.clone());
3458                // SAFETY: We don't touch the root while the handle is alive.
3459                let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3460                *root = Some(node.forget_type());
3461                *self.length += 1;
3462                self.current = Some(handle.left_edge());
3463                return;
3464            }
3465            Some(current) => current,
3466        };
3467
3468        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3469            drop(ins.left);
3470            // SAFETY: The handle to the newly inserted value is always on a
3471            // leaf node, so adding a new root node doesn't invalidate it.
3472            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3473            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3474        });
3475        self.current = Some(handle.left_edge());
3476        *self.length += 1;
3477    }
3478
3479    /// Inserts a new key-value pair into the map in the gap that the
3480    /// cursor is currently pointing to.
3481    ///
3482    /// After the insertion the cursor will be pointing at the gap after the
3483    /// newly inserted element.
3484    ///
3485    /// # Safety
3486    ///
3487    /// You must ensure that the `BTreeMap` invariants are maintained.
3488    /// Specifically:
3489    ///
3490    /// * The key of the newly inserted element must be unique in the tree.
3491    /// * All keys in the tree must remain in sorted order.
3492    #[unstable(feature = "btree_cursors", issue = "107540")]
3493    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3494        let edge = match self.current.take() {
3495            None => {
3496                // SAFETY: We have no other reference to the tree.
3497                match unsafe { self.root.reborrow() } {
3498                    root @ None => {
3499                        // Tree is empty, allocate a new root.
3500                        let mut node = NodeRef::new_leaf(self.alloc.clone());
3501                        // SAFETY: We don't touch the root while the handle is alive.
3502                        let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3503                        *root = Some(node.forget_type());
3504                        *self.length += 1;
3505                        self.current = Some(handle.right_edge());
3506                        return;
3507                    }
3508                    Some(root) => root.borrow_mut().last_leaf_edge(),
3509                }
3510            }
3511            Some(current) => current,
3512        };
3513
3514        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3515            drop(ins.left);
3516            // SAFETY: The handle to the newly inserted value is always on a
3517            // leaf node, so adding a new root node doesn't invalidate it.
3518            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3519            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3520        });
3521        self.current = Some(handle.right_edge());
3522        *self.length += 1;
3523    }
3524
3525    /// Inserts a new key-value pair into the map in the gap that the
3526    /// cursor is currently pointing to.
3527    ///
3528    /// After the insertion the cursor will be pointing at the gap before the
3529    /// newly inserted element.
3530    ///
3531    /// If the inserted key is not greater than the key before the cursor
3532    /// (if any), or if it not less than the key after the cursor (if any),
3533    /// then an [`UnorderedKeyError`] is returned since this would
3534    /// invalidate the [`Ord`] invariant between the keys of the map.
3535    #[unstable(feature = "btree_cursors", issue = "107540")]
3536    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3537        if let Some((prev, _)) = self.peek_prev() {
3538            if &key <= prev {
3539                return Err(UnorderedKeyError {});
3540            }
3541        }
3542        if let Some((next, _)) = self.peek_next() {
3543            if &key >= next {
3544                return Err(UnorderedKeyError {});
3545            }
3546        }
3547        // SAFETY: Ensured by checks above.
3548        unsafe {
3549            self.insert_after_unchecked(key, value);
3550        }
3551        Ok(())
3552    }
3553
3554    /// Inserts a new key-value pair into the map in the gap that the
3555    /// cursor is currently pointing to.
3556    ///
3557    /// After the insertion the cursor will be pointing at the gap after the
3558    /// newly inserted element.
3559    ///
3560    /// If the inserted key is not greater than the key before the cursor
3561    /// (if any), or if it not less than the key after the cursor (if any),
3562    /// then an [`UnorderedKeyError`] is returned since this would
3563    /// invalidate the [`Ord`] invariant between the keys of the map.
3564    #[unstable(feature = "btree_cursors", issue = "107540")]
3565    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3566        if let Some((prev, _)) = self.peek_prev() {
3567            if &key <= prev {
3568                return Err(UnorderedKeyError {});
3569            }
3570        }
3571        if let Some((next, _)) = self.peek_next() {
3572            if &key >= next {
3573                return Err(UnorderedKeyError {});
3574            }
3575        }
3576        // SAFETY: Ensured by checks above.
3577        unsafe {
3578            self.insert_before_unchecked(key, value);
3579        }
3580        Ok(())
3581    }
3582
3583    /// Removes the next element from the `BTreeMap`.
3584    ///
3585    /// The element that was removed is returned. The cursor position is
3586    /// unchanged (before the removed element).
3587    #[unstable(feature = "btree_cursors", issue = "107540")]
3588    pub fn remove_next(&mut self) -> Option<(K, V)> {
3589        let current = self.current.take()?;
3590        if current.reborrow().next_kv().is_err() {
3591            self.current = Some(current);
3592            return None;
3593        }
3594        let mut emptied_internal_root = false;
3595        let (kv, pos) = current
3596            .next_kv()
3597            // This should be unwrap(), but that doesn't work because NodeRef
3598            // doesn't implement Debug. The condition is checked above.
3599            .ok()?
3600            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3601        self.current = Some(pos);
3602        *self.length -= 1;
3603        if emptied_internal_root {
3604            // SAFETY: This is safe since current does not point within the now
3605            // empty root node.
3606            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3607            root.pop_internal_level(self.alloc.clone());
3608        }
3609        Some(kv)
3610    }
3611
3612    /// Removes the preceding element from the `BTreeMap`.
3613    ///
3614    /// The element that was removed is returned. The cursor position is
3615    /// unchanged (after the removed element).
3616    #[unstable(feature = "btree_cursors", issue = "107540")]
3617    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3618        let current = self.current.take()?;
3619        if current.reborrow().next_back_kv().is_err() {
3620            self.current = Some(current);
3621            return None;
3622        }
3623        let mut emptied_internal_root = false;
3624        let (kv, pos) = current
3625            .next_back_kv()
3626            // This should be unwrap(), but that doesn't work because NodeRef
3627            // doesn't implement Debug. The condition is checked above.
3628            .ok()?
3629            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3630        self.current = Some(pos);
3631        *self.length -= 1;
3632        if emptied_internal_root {
3633            // SAFETY: This is safe since current does not point within the now
3634            // empty root node.
3635            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3636            root.pop_internal_level(self.alloc.clone());
3637        }
3638        Some(kv)
3639    }
3640}
3641
3642impl<'a, K: Ord, V, A: AllocatorClone> CursorMut<'a, K, V, A> {
3643    /// Inserts a new key-value pair into the map in the gap that the
3644    /// cursor is currently pointing to.
3645    ///
3646    /// After the insertion the cursor will be pointing at the gap after the
3647    /// newly inserted element.
3648    ///
3649    /// # Safety
3650    ///
3651    /// You must ensure that the `BTreeMap` invariants are maintained.
3652    /// Specifically:
3653    ///
3654    /// * The key of the newly inserted element must be unique in the tree.
3655    /// * All keys in the tree must remain in sorted order.
3656    #[unstable(feature = "btree_cursors", issue = "107540")]
3657    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3658        // SAFETY: Upheld by caller.
3659        unsafe { self.inner.insert_after_unchecked(key, value) }
3660    }
3661
3662    /// Inserts a new key-value pair into the map in the gap that the
3663    /// cursor is currently pointing to.
3664    ///
3665    /// After the insertion the cursor will be pointing at the gap after the
3666    /// newly inserted element.
3667    ///
3668    /// # Safety
3669    ///
3670    /// You must ensure that the `BTreeMap` invariants are maintained.
3671    /// Specifically:
3672    ///
3673    /// * The key of the newly inserted element must be unique in the tree.
3674    /// * All keys in the tree must remain in sorted order.
3675    #[unstable(feature = "btree_cursors", issue = "107540")]
3676    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3677        // SAFETY: Upheld by caller.
3678        unsafe { self.inner.insert_before_unchecked(key, value) }
3679    }
3680
3681    /// Inserts a new key-value pair into the map in the gap that the
3682    /// cursor is currently pointing to.
3683    ///
3684    /// After the insertion the cursor will be pointing at the gap before the
3685    /// newly inserted element.
3686    ///
3687    /// If the inserted key is not greater than the key before the cursor
3688    /// (if any), or if it not less than the key after the cursor (if any),
3689    /// then an [`UnorderedKeyError`] is returned since this would
3690    /// invalidate the [`Ord`] invariant between the keys of the map.
3691    #[unstable(feature = "btree_cursors", issue = "107540")]
3692    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3693        self.inner.insert_after(key, value)
3694    }
3695
3696    /// Inserts a new key-value pair into the map in the gap that the
3697    /// cursor is currently pointing to.
3698    ///
3699    /// After the insertion the cursor will be pointing at the gap after the
3700    /// newly inserted element.
3701    ///
3702    /// If the inserted key is not greater than the key before the cursor
3703    /// (if any), or if it not less than the key after the cursor (if any),
3704    /// then an [`UnorderedKeyError`] is returned since this would
3705    /// invalidate the [`Ord`] invariant between the keys of the map.
3706    #[unstable(feature = "btree_cursors", issue = "107540")]
3707    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3708        self.inner.insert_before(key, value)
3709    }
3710
3711    /// Removes the next element from the `BTreeMap`.
3712    ///
3713    /// The element that was removed is returned. The cursor position is
3714    /// unchanged (before the removed element).
3715    #[unstable(feature = "btree_cursors", issue = "107540")]
3716    pub fn remove_next(&mut self) -> Option<(K, V)> {
3717        self.inner.remove_next()
3718    }
3719
3720    /// Removes the preceding element from the `BTreeMap`.
3721    ///
3722    /// The element that was removed is returned. The cursor position is
3723    /// unchanged (after the removed element).
3724    #[unstable(feature = "btree_cursors", issue = "107540")]
3725    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3726        self.inner.remove_prev()
3727    }
3728}
3729
3730/// Error type returned by [`CursorMut::insert_before`] and
3731/// [`CursorMut::insert_after`] if the key being inserted is not properly
3732/// ordered with regards to adjacent keys.
3733#[derive(Clone, PartialEq, Eq, Debug)]
3734#[unstable(feature = "btree_cursors", issue = "107540")]
3735pub struct UnorderedKeyError {}
3736
3737#[unstable(feature = "btree_cursors", issue = "107540")]
3738impl fmt::Display for UnorderedKeyError {
3739    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3740        write!(f, "key is not properly ordered relative to neighbors")
3741    }
3742}
3743
3744#[unstable(feature = "btree_cursors", issue = "107540")]
3745impl Error for UnorderedKeyError {}
3746
3747#[cfg(test)]
3748mod tests;